标签页代码如下:
// 注意:el-form中的数据绑定不可以用v-model,要使用:model
<el-form ref="ruleFormRef" :rules="rules" :model="userTemp" label-width="80px">
<el-row :gutter="20">
<el-col :span="12">
<el-form-item label="账号" prop="username">
<el-input v-model="userTemp.username"/>
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item label="姓名" prop="name">
<el-input v-model="userTemp.name"/>
</el-form-item>
</el-col>
</el-row>
</el-form>
<el-button type="primary" @click="confirmAdd(ruleFormRef)">确定</el-button>
语法糖代码如下:
<script setup lang="ts">
import {ElMessage, ElMessageBox, FormRules, FormInstance} from "element-plus"
const userTemp = ref({
username: '',
name: '',
})
// 自定义检验规则
const usernameCheck = (rule, value, callback) => {
if (value === undefined) {
callback(new Error('账号不能为空'))
} else {
if (value === '') {
callback(new Error('账号不能为空'))
} else {
if (value !== '') {
let reg = /^[A-Za-z0-9]+$/
if (!reg.test(value)) {
callback(new Error('账号只能是字母或数字'))
}
}
callback()
}
}
}
const rules = ref<FormRules<typeof userTemp>>({
username: [{required: true, validator: usernameCheck, trigger: 'blur'}],
name: [{required: true, message: '姓名不能为空', trigger: 'blur'}]
})
// 该名称要和标签中ref的名称一样
const ruleFormRef = ref(null)
const confirmAdd = (formEl: FormInstance | undefined) => {
if (!formEl) return
formEl.validate((valid) => {
if (valid) {
// 验证成功进入这里
console.log('验证成功')
} else {
console.log('error submit!')
return false
}
})
}
// 重置验证规则,调用resetForm(ruleFormRef.value)
const resetForm = (formEl: FormInstance | undefined) => {
if (!formEl) return
formEl.resetFields()
}
</script>