如你有一个表单,表单内容是对象,但是对象内还有可动态循环的数组进行动态表单校验。
效果如图:查看源码
页面内容:
<div class="arrForm-Box">
<el-form :model="state.formData" :rules="rules" ref="formDataRef" label-width="80">
<el-row :gutter="35">
<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb10">
<el-form-item label="账号" prop="account">
<el-input v-model="state.formData.account" placeholder="账号" clearable />
</el-form-item>
</el-col>
<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb10">
<el-form-item label="密码" prop="password">
<el-input v-model="state.formData.password" type="password" placeholder="密码" clearable />
</el-form-item>
</el-col>
<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
<el-button size="small" class="w100" @click="add">新增</el-button>
</el-col>
<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
<el-row :gutter="35" v-for="(v, k) in state.formData.userList" :key="k">
<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
<el-form-item label="姓名" :prop="`userList[${k}].name`" :rules="[{ required: true, message: `请输入姓名` }]">
<template #label>
<el-button type="danger" :icon="Delete" circle plain size="small" @click="remove(k)" />
<span class="ml5">姓名</span>
</template>
<el-input v-model="state.formData.userList[k].name" placeholder="姓名" clearable />
</el-form-item>
</el-col>
<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
<el-form-item label="年龄" :prop="`userList[${k}].age`" :rules="[{ required: true, message: `请输入年龄` },{ type: 'number', message: '请输入数字' }]">
<el-input v-model.number="state.formData.userList[k].age" placeholder="年龄" clearable />
</el-form-item>
</el-col>
</el-row>
</el-col>
<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
<el-form-item>
<el-button type="primary" @click="submitForm()">提交</el-button>
<el-button @click="resetForm()">重置</el-button>
</el-form-item>
</el-col>
</el-row>
</el-form>
</div>
逻辑代码:
表单对象单独写一个rules,里面的数组表单可直接索引动态绑定prop来设置
import {ref, reactive} from "vue";
import {Delete, Plus} from '@element-plus/icons-vue'
const formDataRef = ref(null);
const state = reactive({
formData: {
account: "",
password: "",
userList: []
}
})
/* 规则 */
const rules = reactive({
account: [
{required: true,message: '请输入账号'},
],
password: [
{required: true,message: '请输入密码'},
],
})
/* 新增 */
const add = () => {
if (state.formData.userList == undefined) state.formData.userList = [];
state.formData.userList?.push({});
};
/* 删除 */
const remove = (index) => {
state.formData.userList.splice(index, 1);
}
/* 提交 */
const submitForm = () => {
formDataRef.value.validate(async (valid) => {
if (!valid) return;
console.log('submit: ',state.formData);
})
}
/* 重置 */
const resetForm = () => {
formDataRef.value.resetFields();
}