问题:Element UI使用表单校验功能控制台出现Cannot read properties of undefined (reading 'validate')报错
解决:在 <el-form :model="form" :rules="rules">添加 ref="form",form为自定义的表单名称
<el-form :model="form" :rules="rules" ref="form"></l-form>
完整案例
添加/修改表单代码
<!-- 新增/更新 --><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
<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 = falseresolve()}else{this.$message.error(res.message.message)resolve()}})})},// 取消resetForm(form) {this.dialogFormVisible = falsethis.$refs[form].resetFields();},}}
</script>