element-ui动态表单验证
由于项目中固定标签的数据是由后端查询回来的数组,需要进行表单验证,代码如下:
<template> <div class="form"> <el-form ref="basicForm" :model="formData" :rules="rules" > <template v-for="(item, index) in formData.datas"> <el-form-item v-if="item.name === '名称'" :prop="`datas[${index}].itemContent`" label="名称" :rules="nameRule" > <el-input v-model="item.itemContent" /> </el-form-item> </template> <template v-for="(item, index) in formData.datas"> <el-form-item v-if="item.name === '地址'" :prop="`datas[${index}].itemContent`" label="地址" :rules="addressRule" > <el-input v-model="item.itemContent" /> </el-form-item> </template> </el-form> </div> </template> <script> export default{ data() { return { formData: { datas: [ { name: '名称', itemContent: '张三' }, { name: '地址', itemContent: '上海' }, ] }, rules: {}, valueRule: [{ validator: this.checkName, trigger: 'blur' }], addressRule: [{ validator: this.checkAddress, trigger: 'blur' }] } }, methods: { checkName () { //验证方法 }, checkAddress() { //验证方法 } } } </script>
注意: :prop="`datas[${index}].itemContent`"中itemContent必须与数组中属性值itemContent相对应