模拟数据
tableData: [{name: "系统1",score: 0,children:[{name: "一号子系统",score: 0,}]},{name: "系统2",score: 0,children:[{name: "3号子系统",score: 0,}]},{name: "系统3",score: 0,children:[{name: "5号子系统",score: 0,}]}
]
关键代码-html
<el-form class="non-static" ref="form" :model="{tableData:tableData}"><!-- 表头 --><div class="item"><div class="text">名字</div><div class="input">分数</div></div><!-- 表格行 --><div class="item" v-for="(level,index) in tableData" :key="index"><!-- 标签 --> <div class="text">{{level.name}}</div><!-- 输入框 --> <el-form-item :prop="'tableData.' + index + '.score'" :rules="rules.age"><el-input type="number" v-model.number="level.score" class="input">{{level.score}}</el-input></el-form-item><!-- 嵌套子元素 --><div class="item" v-for="(level2,i) in level.children" :key="index+i"><div class="text">{{level2.name}}</div><el-form-item :prop="'tableData.' + index + '.children.'+ i + '.score'" :rules="rules.age"><el-input type="number" v-model.number="level2.score" class="input">{{level2.score}}</el-input></el-form-item></div></div>
</el-form>
data() {var checkAge = (rule, value, callback) => {if (value == 0) {// 验证失败return callback(new Error('年龄不能为空'));}// 验证成功callback();}return {rules: {age: [{ validator: checkAge, trigger: 'submit' }]}};},methods: {submit() {// 表单验证APIthis.$refs.form.validate((valid) => {if (valid) {console.log("提交");}else {console.log("不提交");}});},}
最重要的几处代码
还有值得注意的是:
在el-input元素处添加了两个声明类型为number的语法
- type=“number”
- v-model.number
没有这两个会报“xxx not is a string”,并且不会触发submit的表单验证。