前言
习惯了 vue2 的 this,而 vue3 没有 this,element 组件库也不再像以前那样复制粘贴即可,路漫漫其修远兮,慢慢积累ing。
由于无法像 vue2 一样通过 this.$refs 来获取表单DOM,所以我们需要借助 vue3 的 ref 来获取表单DOM,对此还有不明白的可先查阅 vue3 通过 ref 获取 DOM。
vue3 使用校验规则表单
<template>
<el-form :rules="uploadFormRules" ref="uploadForm" :model="uploadFormData" label-width="70px">
<el-form-item label="组别ID" prop="groupId">
<el-input v-model="uploadFormData.groupId" placeholder="请输入组别ID"></el-input>
</el-form-item>
<el-form-item label="组别名" prop="groupName">
<el-input v-model="uploadFormData.groupName" placeholder="请输入组别名"></el-input>
</el-form-item>
<el-form-item label="是否显示" prop="groupStatus">
<el-switch v-model="uploadFormData.groupStatus" />
</el-form-item>
<el-button size="medium" @click="resetForm('uploadForm')">取 消</el-button>
<el-button size="medium" type="primary" @click="submitForm">确 定</el-button>
</el-form-item>
</el-form>
</template>
<script lang="ts">
import {defineComponent, ref} from 'vue';
export default defineComponent({
name: 'UserGroup',
setup() {
const uploadObj = {groupId: '', groupName: '', groupStatus: true} // 新增组别表单包含的参数
const uploadForm = ref() // 新增组别表单 DOM
const uploadFormData = ref({...uploadObj}) // 新增组别表单的信息
const uploadFormRules = ref({
groupId: [
{ required: true, message: '请输入组别ID', trigger: 'blur' }
],
groupName: [
{ required: true, message: '请输入组别名', trigger: 'blur' },
{ min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
]
}) // 新增组别表单规则
// 重置表单,呃,这里暂时不会像 vue2 那样通过 this.$refs[formName] 动态实现重置各个表单
const resetForm = (formName: string) => {
if (formName === 'uploadForm') {
uploadForm.value.resetFields()
}
}
// 提交表单
const submitForm = () => {
uploadForm.value.validate((valid: any) => {
if (valid) {
console.log('submit')
} else {
console.log('error submit')
return false
}
})
}
return {
uploadForm,
uploadFormData,
uploadFormRules,
resetForm,
submitForm
}
}
})
</script>