先看效果图:
以上是一个表单,俱乐部的名称是必填的;俱乐部成员是一个table数据,至少有一个,且可以点击添加按钮添加多个 ,但动态添加的行都需要进行表单验证。这里演示说明,电话没有做正则验证。代码如下:
<template> <el-dialog :visible.sync="dialogVisible" width="50%"> <el-form ref="myform" :model="myform" label-width="120px" :rules="rules"> <el-form-item label="俱乐部名称" prop="jlbName"> <el-input v-model="myform.jlbName" /> </el-form-item> <el-form-item label="俱乐部成员"> <el-button icon="el-icon-plus" type="success" size="mini" @click="chickPlus">添加</el-button> <el-table :data="myform.userList" align="center"> <el-table-column label="姓名"> <template slot-scope="scope"> <el-form-item :prop="`userList.${scope.$index}.chinaName`" :rules="rules.chinaName"> <el-input v-model="scope.row.chinaName" /> </el-form-item> </template> </el-table-column> <el-table-column label="电话"> <template slot-scope="scope"> <el-form-item :prop="`userList.${scope.$index}.phone`" :rules="rules.phone"> <el-input v-model="scope.row.phone" /> </el-form-item> </template> </el-table-column> </el-table> </el-form-item> </el-form> <div slot="footer" class="dialog-footer"> <el-button @click="dialogVisible = false">取消</el-button> <el-button type="primary" @click="handleCreate">保存</el-button> </div> </el-dialog> </template> <script> export default { data() { return { dialogVisible: true, myform: { jlbName: '', userList: [{ chinaName: '', phone: '' }] }, rules: { jlbName: [{ required: true, message: '必填', trigger: 'blur' }], chinaName: [{ required: true, message: '必填', trigger: 'blur' }], phone: [{ required: true, message: '必填', trigger: 'blur' }], } } }, methods: { //添加一行 chickPlus() { this.myform.userList.push({ chinaName: '', phone: '' }) }, handleCreate() { this.$refs['myform'].validate((valid) => { if (valid) { console.log(this.myform) } }) } }, } </script> <style scoped> </style>
从代码可以看出,在el-form-item标签中嵌套了el-table标签,在el-table中每一列又包含了el-form-item,也就需要对此进行验证。scope.$index表示每一行的索引值,而${scope.$index}结合prop就绑定了每一行每一列的验证。