因为 elementplus 局部只给了 Options API
的写法,故再此记录应用 Composition API
写过的组件的办法。
form 表单相干
当初想要获取 ref 须要进行一下操作
import {ref} from 'vue'
setup () {
// 第一步定义 ref, 名称与 html 中的 ref="yourRef" 统一, 并 return 进来
const yourRef = ref()
// 而后就能够和 vue2 中的 ref 一样应用了
// 提交表单
const saveOneBlog = () => {console.log('listen formRef', formRef)
formRef.value.validate(async (valid) => {if (valid) {const res = await api(params)
console.log(res)
}
})
}
// 重置表单
const reset = () => {yourRef.value.resetFields()
}
return {yourRef}
}
表单局部代码 html
局部
<el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
<el-form-item label="名称" prop="blogTitle">
<el-input v-model="form.blogTitle" placeholder="请输出博客名称"></el-input>
</el-form-item>
<el-form-item label="类型" prop="blogTypeId">
<el-select v-model="form.blogTypeId" placeholder="抉择博客类型">
<el-option
v-for="item in blogTypeList"
:key="item.blogTypeId"
:label="item.typeName"
:value="item.blogTypeId">
</el-option>
</el-select>
</el-form-item>
<el-form-item label="内容" prop="blogContent">
<v-md-editor v-model="form.blogContent" height="400px" ></v-md-editor>
</el-form-item>
<el-form-item label="是否可见" prop="isShow">
<el-switch v-model="form.isShow" active-color="#13ce66" inactive-color="#ff4949"> </el-switch>
</el-form-item>
<el-form-item v-show="isEdit" label="创立工夫" prop="createTime">
{{form.createTime}}
</el-form-item>
<el-form-item v-show="isEdit" label="最初批改工夫" prop="lastUpdateTime">
{{form.lastUpdateTime}}
</el-form-item>
</el-form>
<div class="g-line"></div>
<div class="footer-btn">
<el-button type="primary" @click="resetForm">reset</el-button>
<el-button type="primary">Save and add aother</el-button>
<el-button type="primary" @click="saveOneBlog">Save</el-button>
</div>
script
局部
setup () {
// form dom
const formRef = ref()
// form data
const formData = reactive({
form: {
blogTitle: '',
blogTypeId: '',
blogContent: '',
isShow: true,
createTime: '',
lastUpdateTime: ''
},
blogTypeList: [],
rules: {blogTitle: [{ required: true, message: '请输出博客名称', trigger: 'blur'}],
blogTypeId: [{required: true, message: '请抉择博客类型', trigger: 'change'}],
blogContent: [{required: true, message: '请输出博客内容', trigger: 'blur'}]
}
})
// submit form data
const saveOneBlog = () => {console.log('listen formRef', formRef)
formRef.value.validate(async (valid: any) => {if (valid) {
const params = {
blogTitle: formData.form.blogTitle,
blogTypeId: formData.form.blogTypeId,
blogContent: formData.form.blogContent
}
const res = await addOneBlogApi(params)
if (res.code === 0) {ElMessage.success('增加胜利')
} else {ElMessage.error(res.message)
}
}
})
}
// reset form
const resetForm = () => {formRef.value.resetFields()
}
const tempData = reactive({isEdit: false})
onMounted(async () => {const res = await getBlogTypeDictApi()
if (res.code === 0) {formData.blogTypeList = res.data}
})
return {...toRefs(formData),
...toRefs(tempData),
saveOneBlog,
resetForm,
formRef
}
}