问题:Element UI使用表单校验功能控制台出现Cannot read properties of undefined (reading 'validate')报错
解决:在 <el-form :model="form" :rules="rules">添加 ref="form",form为自定义的表单名称
html
<el-form :model="form" :rules="rules" ref="form"></l-form>
完整案例
添加/修改表单代码
html
<!-- 新增/更新 -->
<div>
<el-dialog :title="(form.id == null ? '新增' : '更新')" :visible.sync="dialogFormVisible" width="40%">
<el-form :model="form" :rules="rules" ref="form">
<el-form-item label="学号" prop="number" label-width="20%">
<el-input v-model="form.number" autocomplete="off" placeholder="请输入学号" style="width:80%"/>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="resetForm('form')">取 消</el-button>
<el-button type="primary" @click="submit('form')">确 定</el-button>
</div>
</el-dialog>
</div>
js
javascript
<script>
export default {
data() {
return {
// 表单
form:{},
// 表单模态框
dialogFormVisible:false,
// 新增/更新表单校验
rules: {
number: [
{ required: true, message: '学号不能为空', trigger: 'blur' }
],
},
}
}
methods:{
// 提交表单数据
async submit(form){
this.$refs[form].validate(async (valid) => {
if (valid) {
await this.apiInsert()
this.select()
}
})
},
apiInsert(){
return new Promise(resolve => {
insert(this.form).then(res => {
if(res.code === 200){
this.dialogFormVisible = false
resolve()
}else{
this.$message.error(res.message.message)
resolve()
}
})
})
},
// 取消
resetForm(form) {
this.dialogFormVisible = false
this.$refs[form].resetFields();
},
}
}
</script>