效果:
引用CSS、JS:
Vue、element-ui、Axios
treeTable: https://github.com/ProsperLee/element-tree-grid
模拟根据父id请求子数据的JSON:
1 // data.json
2 [{
3 "id": "a1",
4 "name": "一级-1",
5 "parentId": "000"
6 }]
7
8 // node.json
9 [{
10 "id": "123",
11 "name": "二级-1-1",
12 "parentId": "a1"
13 }, {
14 "id": "123",
15 "name": "二级-1-2",
16 "parentId": "a1"
17 }, {
18 "id": "123",
19 "name": "二级-1-3",
20 "parentId": "a1"
21 }]
HTML部分:
1 <div id="app">
2 <el-table :data="data">
3 <el-table-column type="index" label="#"></el-table-column>
4 <el-table-tree-column :remote="remote" prop="name" parent-key="parentId" label="NAME"></el-table-tree-column>
5 <el-table-column prop="name" label="NAME"></el-table-column>
6 </el-table>
7 </div>
JS部分:// 注意属性表格要显示展开箭头需要加入 child_num 属性
1 new Vue({
2 el: "#app",
3 data: {
4 data: []
5 },
6 methods: {
7 remote(row, callback) {
8 var that = this;
9 axios.get("./json/node.json", null)
10 .then(function (response) {
11 row.child_num = response.data.length; // 父级有几个孩子
12 var count = row.depth+1;
13 response.data.forEach((element)=>{ // 循环孩子
14 // element.child_num = 1;
15 element.depth = count;
16 })
17 var len = response.data.length;
18 for(var i = 0; i < len; i++){
19 if(response.data[i].parentId == row.id){
20 response.data.unshift(0,0); // 数组前面添加元素
21 Array.prototype.splice.apply(that.data, response.data); // 指定位置拼接两个数组
22 break;
23 }
24 }
25 callback(that.data.filter(f => f['parentId'] == row['id']))
26 })
27 .catch(function (error) {
28 console.log(error);
29 })
30 },
31 // 获取根节点
32 getParentIdData(){
33 var that = this;
34 axios.get("./json/data.json", null)
35 .then(function (response) {
36 response.data.forEach(element => {
37 element.child_num = 1;
38 element.depth = 0;
39 });
40 that.data = response.data;
41 })
42 .catch(function (error) {
43 console.log(error);
44 })
45 }
46 },
47 created() {
48 this.getParentIdData();
49 },
50 })