首先須要生成一個序號用來肯定表單驗證的目標row,經過廣度優先遍歷,以1,1.1,1.1.1的規則對樹形列表生成肯定惟一值的索引,由於列表自身能夠作CURD,所以須要每次列表的item增長或減小時從新調用生成索引的方法。javascript
const setIndex = (data) => { let queue = [...data]; let loop = 0; while (queue.length > 0) { loop++ [...queue].forEach((child, i) => { queue.shift() if (loop == 1) { child.customIndex = i + 1 + ""; child.currentIndex = i; } if (child.children && child.children.length > 0) { child.dataType = 1 for (let ci = 0; ci < child.children.length; ci++) { child.children[ci].currentIndex = ci child.children[ci].customIndex = child.customIndex + "." + (ci + 1) } queue.push(...child.children) } else { child.dataType = 2 } }) } } const rows = [ { id: "1", date: "2016-05-02", name: "王小虎1", address: "上海市普陀區金沙江路 1518 弄", children: [ { name: "233", customIndex: "1.1", children: [{name: "9"}] }, { name: "7771", customIndex: "1.2", children: [ { name: "9" }, { name: "9", }] } ] }, { id: "2", date: "2016-05-04", name: "王小虎2", address: "上海市普陀區金沙江路 1517 弄", children: [] }, ] setIndex(rows)
要想實現對錶格的表單驗證,須要用form-item將整個表格包裹,而後在以子集的方式將每一列用form-item包裹。java
<el-form ref="form" :model="form" label-width="80px" :rules="rules"> <el-form-item label-width="0" prop="rows"> <el-table> </el-table> </el-form-item> </el-form>
<el-table-column prop="name" label="姓名" sortable width="180"> <template v-slot="{$index, row}"> {{`rows${getPathByKey(row.customIndex,"customIndex",form.rows)}.name`}} <el-form-item label-width="0" :rules="rules.name" :prop="`${row.customIndex!=='tempIndex'?`rows${getPathByKey(row.customIndex,'customIndex',form.rows)}.name`:''}`"> <el-input v-model="row.name"></el-input> </el-form-item> </template> </el-table-column>
實現方式,表單校驗本質是對於目標數據的路徑查找,當el-form-item 上的prop匹配不到正確的目標是的時候就不能正常觸發校驗
所以,須要記錄每個row上面的屬性路徑,即實現記錄每一行中屬性(name,address)路徑的方法。node
const getPathByKey = (value, key, arr) => { let temppath = []; let realPath = "" try { function getNodePath(node) { temppath.push(node.currentIndex); //找到符合條件的節點,經過throw終止掉遞歸 if (node[key] === value) { temppath.forEach((v, i) => { if (i == 0) { realPath += "." + v } else { realPath += `.children.${v}` } }) // temppath = temppath.join(",") throw ("GOT IT!"); // return; } if (node.children && node.children.length > 0) { for (var i = 0; i < node.children.length; i++) { getNodePath(node.children[i]); } //當前節點的子節點遍歷完依舊沒找到,則刪除路徑中的該節點 temppath.pop(); } else { //找到葉子節點時,刪除路徑當中的該葉子節點 temppath.pop(); } } for (let i = 0; i < arr.length; i++) { getNodePath(arr[i]); } } catch (e) { return realPath; } },
將每一列須要驗證的item,路徑查找好以後,form就能夠具體監控到全部的表格輸入,並觸發正確的驗證了,如圖:
demo參考git