之前使用表单验证时,都是对象形式,比较简单,直接按官网demo来即可满足要求,官网链接如下:
https://element-plus.gitee.io/zh-CN/component/form.html
代码如下:
<template> <div> <el-form ref="ruleForm" :model="myForm" :rules="rules"> <el-form-item label="姓名" prop="name"> <el-input v-model="myForm.name"></el-input> </el-form-item> </el-form> </div> </template> <script> export default { name: "menu1-1", data () { return { myForm: { name: '', }, rules: { name: [ { required: true, message: '请输入姓名', trigger: 'blur' }, { min: 2, max: 10, message: '长度在2到10个字', trigger: 'blur' } ] } } } } </script>
遍历时表单验证
提示:
1、每个form-item都需要rules,而不是像之前把rules放到el-form那一行
2、props需要采用模板语法 list.${index} 的形式,使用item匹配不到,如下方代码所示
<template> <div> <el-form ref="ruleForm" :model="myForm" > <el-form-item label="姓名" prop="name" :rules="rules.name"> <el-input v-model="myForm.name"></el-input> </el-form-item> <div v-for="(item, index) in myForm.list" :key="index"> <el-form-item label="科目" :prop="`list.${index}.subject`" :rules="rules.subject"> <el-select v-model="item.subject"> <el-option v-for="ite in subjectList" :key="ite.label" :label="ite.label" :value="ite.id" /> </el-select> </el-form-item> </div> </el-form> <el-button @click="onSubmit">提交</el-button> </div> </template> <script> export default { name: "menu1-1", data () { return { myForm: { name: '', list: [ { subject: '' }, { subject: '' }, { subject: '' } ] }, subjectList: [ {id: '1', label: '语文'}, {id: '2', label: '数学'}, {id: '3', label: '英语'} ], rules: { name: [ { required: true, message: '请输入姓名', trigger: 'blur' }, { min: 2, max: 10, message: '长度在2到10个字', trigger: 'blur' } ], subject: [ { required: true, message: '请选择科目', trigger: 'change' } ] } } }, methods: { onSubmit () { this.$refs.ruleForm.validate(valid => { if (valid) { console.log('提交的form表单', this.myForm) } }) } } } </script>
最重要的代码就是这一句,如下图所示
如果list以下还有数组需要遍历,也就是两层遍历,props则可以这么写。如果是三层遍历的话,那就得考虑优化数据结构了
:prop="`list.${index}.${i}.subject`" // i是list数组下的数组键值
好了,以上就是遍历时表单验证处理的所有内容了
标签:遍历,name,list,表单,trigger,message,element,subject From: https://www.cnblogs.com/yyzhiqiu/p/17620739.html