遇到一个问题,适用elementUI的表单校验时,select校验总是不通过
代码如下:
<el-form label-width="100px" :model="addForm" :rules="rules" ref="addForm">
<el-form-item label="报表" :label-width="formLabelWidth" prop="report">
<el-select v-model="addForm.reportValue" placeholder="请选择报表" style="width:275px">
<el-option v-for="item in addForm.reportOptions" :label="item.name" :value="(item.id)*1">
</el-option>
</el-select>
</el-form-item>
</el-form>
<script>
export default {
data() {
return {
addForm: {
reportValue: '',
},
rules: {
report: [ { required: true, message: '请选择报表', trigger: 'change' } ],
}
}
}
}
</script>
总是报错,就算选择了还是报错如下图经过多方排查,终于找到问题所在:
重点啦!重点啦!
表单中每个item项v-model绑定的data的字段,必须必须必须,和rules中的对应字段,名字名字名字,一样,否则校验时取不到值(undefined),所以无论输入什么或者选择什么都校验不过。
正确代码方式如下
<el-form label-width="100px" :model="addForm" :rules="rules" ref="addForm">
<el-form-item label="报表" prop="reportValue">
<el-select v-model="addForm.reportValue" placeholder="请选择报表">
<el-option v-for="item in addForm.reportOptions" :label="item.name" :value="(item.id)*1">
</el-option>
</el-select>
</el-form-item>
</el-form>
<script>
export default {
data() {
return {
addForm: {
reportValue: '',
},
rules: {
reportValue: [ { required: true, message: '请选择报表', trigger: 'change' } ],
}
}
}
}
</script>