赞
踩
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/element-ui/2.15.1/theme-chalk/index.min.css" /> <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.9/vue.min.js"></script> <script src="https://cdn.bootcdn.net/ajax/libs/element-ui/2.15.1/index.min.js"></script> </head> <body> <div id="app" style="width: 800px; height: 400px"> <!-- 整个表单 --> <el-form :model="formInfo" size="mini" :rules="rules" ref="formInfo" inline> <!-- 固定值 公共部分--> <el-form-item label="名称" prop="name"> <el-input v-model="formInfo.name" size="mini" /> </el-form-item> <!-- 循环值 prop为'userList.'+index+'.name' .每一个循环中的<el-form-item>都需要加:rules--> <div v-for="(item, index) in formInfo.list" :key="index" class="inline"> <el-form-item label="账号:" :prop="'list.'+ index +'.username'" :rules="rules.username"> <el-input v-model="item.username" size="mini" /> </el-form-item> <el-form-item label="密码:" :prop="'list.'+ index +'.password'" :rules="rules.password"> <el-input v-model="item.password" type="password" /> </el-form-item> <el-form-item label="手机号:" :prop="'list.'+ index +'.phone'" :rules="rules.phone"> <el-input v-model="item.phone" size="mini" /> </el-form-item> </div> </el-form> <el-button type="primary" @click="add">添加</el-button> <el-button type="primary" @click="submit">提交</el-button> </div> <script> const lx = new Vue({ el: '#app', data() { return { rules: { name: [ { required: true, message: '请输入名称', trigger: 'blur', }, ], phone: [ { required: true, message: '请输入账号手机号', trigger: 'blur', }, ], username: [ { required: true, message: '请输入账号名称', trigger: 'blur', }, ], password: [ { required: true, message: '请输入密码', trigger: 'blur', }, ], }, // 添加校验 formInfo: { name: '', list: [ { phone: '', username: '', password: '', }, ], }, } }, watch: {}, computed: {}, methods: { // 新增 add() { this.formInfo.list.push({ phone: '', username: '', password: '' }) }, // 提交 submit() { let isValid = false this.$refs.formInfo.validate((valid) => { if (valid) isValid = true }) if (!isValid) return }, }, created() {}, }) </script> <style> .inline { display: flex; } </style> </body></html>