1,准备工作,后台准备这样一个接口,即根据 id 能请求得到下一层的数据,没有层级关系,children字段为空。

2,表格树形数据的动态加载:先设置lazy和绑定load函数

 <el-table
      v-loading="loading"
      :data="deptList"
      row-key="deptId"
      lazy
      :load="treeLoad"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >

注意::tree-props="{ children: 'children', hasChildren: 'hasChildren' }"   必须加上这串代码,当节点中能查出子节点的数据时,接口需要返回一个 hasChildren:true 的字段。相反,如果节点已经是叶子节点,则这个字段为:hasChildren:false,新增hasChildren字段的目的是用来判断是否为叶子节点从而控制是否有展开数据的小箭头。

3、初始化第一层的数据:

 created() {
    this.getTreeList();
  },

 // 初始化tree
    getTreeList() {
      this.loading = true;
      this.deptList = [];
      listDept(Object({ parentId: 0 })).then((response) => {
        this.deptList = response.data;
        this.loading = false;
      });
    },

本例子中,通过传 parentId = 0 的方式来得到了第一层数据。

4,动态加载函数:

  // 树形动态加载表单数据:
    treeLoad(tree, treeNode, resolve) {
      setTimeout(() => {
        listDept(Object({ parentId: tree.deptId })).then((res) => {
          return resolve(res.data);
        });
      }, 222);
    },

 其中 tree.deptId 就是获取当前点击的 deptId 字段。

至此,表格的树形数据动态加载已经完成。

扩展功能:

点击每一行就能展开数据而不用只点前面小箭头才生效。

1、table中添加 row-click 绑定行点击事件

 <el-table
      v-loading="loading"
      :data="deptList"
      row-key="deptId"
      lazy
      :load="treeLoad"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      @row-click="getOpenDetail"  //添加这一行绑定一个事件
    >

2、展开节点的事件:

 // 点击展开节点
    getOpenDetail(row, column, event) {
      if (event.currentTarget.querySelector(".el-table__expand-icon")) {
        event.currentTarget.querySelector(".el-table__expand-icon").click();
      }
    },

end!   

GitHub 加速计划 / eleme / element
54.06 K
14.63 K
下载
A Vue.js 2.0 UI Toolkit for Web
最近提交(Master分支:1 个月前 )
c345bb45 5 个月前
a07f3a59 * Update transition.md * Update table.md * Update transition.md * Update table.md * Update transition.md * Update table.md * Update table.md * Update transition.md * Update popover.md 5 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐