最近在写项目的时候,使用后端的数据v-for循环渲染el-form-item,但是每一项要加上rules表单验证,找到了一种可以动态绑定的写法
element-puls官网中介绍,要绑定rules,需要加入prop属性,prop是用来匹配rules的
- 首先在el-form总标签中绑定一个rules,给一个el-form-item绑定上,prop的名字要与rules对象和:model="showDataInfo"的键名一致,这样才能匹配上验证规则
//HTML部分
<el-form
size="small"
:model="showDataInfo"
ref="formRef"
:rules="rules"
label-position="left"
label-width="38%"
>
<el-form-item label="点位名称" prop="placeName">
//JS部分 **需要给el-form写一个rules,后面循环的rules才能生效**
const rules = reactive({
placeName: [
{
required: true,
message: "数据不能为空",
trigger: "blur",
},
],
});
- 循环渲染的el-form-item绑定上rules,el-form组件中的prop接收的是一个字符串,这样才能匹配上监听的数据:model="showDataInfo"
<template
v-for="(obj, index) of showDataInfo.equipSettingDetails[0].installParams"
:key="index"
>
<el-form-item
v-if="isShowBindLinkWidth1"
:prop="'equipSettingDetails[0]' + '.installParams.' + index + '.value' "
:rules="isNumRules"
>
//js部分 数值不为空的校验
const isNumRules = [
{ required: true, message: "请输入数据" },
{ type: "number", message: "必须输入数字" },
];
不知道还有没有其他的方法!!!!