效果:
引用CSS、JS:
Vue、element-ui、Axios
treeTable: https://github.com/ProsperLee/element-tree-grid
模拟根据父id请求子数据的JSON:
// data.json
[{
"id": "a1",
"name": "一级-1",
"parentId": "000"
}] // node.json
[{
"id": "123",
"name": "二级-1-1",
"parentId": "a1"
}, {
"id": "123",
"name": "二级-1-2",
"parentId": "a1"
}, {
"id": "123",
"name": "二级-1-3",
"parentId": "a1"
}]
HTML部分:
<div id="app">
<el-table :data="data">
<el-table-column type="index" label="#"></el-table-column>
<el-table-tree-column :remote="remote" prop="name" parent-key="parentId" label="NAME"></el-table-tree-column>
<el-table-column prop="name" label="NAME"></el-table-column>
</el-table>
</div>
JS部分:// 注意属性表格要显示展开箭头需要加入 child_num 属性
new Vue({
el: "#app",
data: {
data: []
},
methods: {
remote(row, callback) {
var that = this;
axios.get("./json/node.json", null)
.then(function (response) {
row.child_num = response.data.length; // 父级有几个孩子
var count = row.depth+1;
response.data.forEach((element)=>{ // 循环孩子
// element.child_num = 1;
element.depth = count;
})
var len = response.data.length;
for(var i = 0; i < len; i++){
if(response.data[i].parentId == row.id){
response.data.unshift(0,0); // 数组前面添加元素
Array.prototype.splice.apply(that.data, response.data); // 指定位置拼接两个数组
break;
}
}
callback(that.data.filter(f => f['parentId'] == row['id']))
})
.catch(function (error) {
console.log(error);
})
},
// 获取根节点
getParentIdData(){
var that = this;
axios.get("./json/data.json", null)
.then(function (response) {
response.data.forEach(element => {
element.child_num = 1;
element.depth = 0;
});
that.data = response.data;
})
.catch(function (error) {
console.log(error);
})
}
},
created() {
this.getParentIdData();
},
})