案例
<template><el-form :model="form" ref="form" label-width="70px"><el-form-item><el-button icon="el-icon-plus" type="primary" plain @click="add">新增</el-button><el-button @click="resetForm('form')">重置</el-button></el-form-item><el-row :gutter="20" v-for="(user, index) in form.userList"><el-col :span="6"><el-form-item label="用户":prop="'userList.' + index + '.userId'":rules="[{required: true, message: '用户不能为空', trigger: ['blur','change']},{ validator: validUser, trigger: ['blur','change'] }]"><el-select v-model="user.userId"placeholder="请选择用户"><el-option v-for="(item,index) in uList":label="item.userName" :value="item.userId" :key="item.userId"></el-option></el-select></el-form-item></el-col><el-col :span="16"><el-form-item label="职能":prop="'userList.' + index + '.roleId'":rules="{required: true, message: '职能不能为空', trigger: ['blur','change']}"><el-selectv-model="user.roleId"multipleplaceholder="请选择职能"><el-optionv-for="dict in dict.type.zhineng_dict":key="dict.value":label="dict.label":value="dict.value"></el-option></el-select></el-form-item></el-col><el-col :span="2" v-if="index !==0"><el-button type="danger" icon="el-icon-delete" plain @click.prevent="handleDelete(user)"></el-button></el-col></el-row></el-form>
</template><script>export default {name: "",dicts: ['zhineng_dict'],data(){return {// 表单form: {userList: []},// 人员列表uList: [],}},mounted() {this.getuList()this.setDefault()},methods: {validUser(rule, value, callback){let userArr = [];this.form.userList.forEach(item => {userArr.push(item.userId)})if (userArr.length !== [...new Set(userArr)].length) {callback(new Error('用户不可以重复'));}else {callback();}},/* 设置默认 */setDefault() {this.form.userList.push({userId: '',roleId: [],key: Date.now()})},/* 删除 */handleDelete(user) {var index = this.form.userList.indexOf(user)if (index !== -1) {this.form.userList.splice(index, 1)}},getuList(){this.uList= response.data;},resetForm(formName) {this.$refs[formName].resetFields();},/* 新增 */add(){this.form.userList.push({userId: '',roleId: [],key: Date.now()});}}
}
</script>
注意
1、select为多选时,默认值需设置为[],否则未填值前就会报校验错误
2、表单必须为object,不能用[ ],会报错