vue 中 表单数据为数组,v-for 循环表单数据
element-ui 中,表单数据一般为对象,但是也有是数组的情况,比如上面图示:账号和密码可以是多个,点击添加会增加一条,点击删除会删除一条
表单数据为
form:{ accounts:[ { account: '', password: '' } ] }
表单中代码
<el-form ref="form" :model="form" label-width="100px" label-suffix=":"> <el-row v-for="(item, index) in form.accounts" :key="index"> <el-col :span="11"> <el-form-item label="系统账号" :prop="`accounts.${index}.account`" :rules="[ {required: true, message: '请输入系统账号', trigger: 'blur'}, {validator: checkAccount, trigger: 'blur'}, {min: 1, max: 16, message: '系统账号至多只能包含16个字符', trigger: 'blur'} ]" > <el-input v-model="item.account" placeholder="请输入系统账号" clearable autocomplete="off" /> </el-form-item> </el-col> <el-col :span="11"> <el-form-item label="账号密码" :prop="`accounts.${index}.password`" :rules="[ {required: true, message: '请输入账号密码', trigger: 'blur'}, {min: 1, max: 16, message: '账号密码至多只能包含16个字符', trigger: 'blur'} ]" > <el-input v-model="item.password" type="password" placeholder="请输入账号密码" clearable autocomplete="new-password" /> </el-form-item> </el-col> <el-col v-if="form.accounts.length >= 2" :span="2"> <div class="form-control-delete"> <el-button icon="el-icon-delete" circle class="btn-editDel" @click="deleteAccount(index)" /> </div> </el-col> </el-row> <div class="form-control-add"> <el-button icon="el-icon-plus" class="btn-add" @click="addAccount">添加账号</el-button> </div> </el-form>
验证两个账号是否重复
data() { const checkAccount = (rule, value, callback) => { if (value === '') { callback(new Error('请输入系统账号')) } else { const len = this.form.accounts.length if (len <= 1) { callback() } else { const allAccount = this.form.accounts.map(v => v.account) const len = allAccount.length const filterAccount = allAccount.filter(v => v !== value) if (len - 1 === filterAccount.length) { callback() } else { callback(new Error('创建的系统账号不能重复!')) } } } } return { checkAccount: checkAccount, } }