解决el-table加载树形数据假死,前端实现懒加载

elementUI文档


    <el-table
      :load="getChildren"
      :data="tableList"
      row-key="deptId"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      lazy
    >
/*
 v-bind:load  展开数据项调用懒加载方法
 row-key  懒加载必填项,对象id
 v-bind:tree-props={
	children  	下级数据集
	hasChildren    判断是否有下级数据并显示展开按钮
 }
 lazy 是否懒加载
*/


<script>
export default {
  name: "Dept",
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 表格树数据
      deptList: [],
      tableList: [],
      lazyTreeNodeMap: new Map(),
      
      // 分页数据
      page: 1,
      size: 10,
      total: 0,
    }
  },
  created: {
  
    this.getList();
     try {
       this.$refs['table'].store.states.lazyTreeNodeMap = {}
     } catch (e) {

     }
	listDept(this.queryParams).then(response => {
       this.deptList = response.data
       this.tableList = this.mapChildren(this.deptList)
     })
  },
  methods: {
  	// 请求表格数据
    getList() {
      this.loading = true;
      this.deptList = []
      this.tableList = []
      this.lazyTreeNodeMap = {}
     // 刷新el-table组件保存的懒加载数据
      try {
        this.$refs['table'].store.states.lazyTreeNodeMap = {}
      } catch (e) {

      }
      listDept(this.queryParams).then(response => {
        this.deptList = response.data
 //		分页处理
 //     this.total = response.data.length
 //     this.tableList = this.mapChildren(this.deptList).splice(0, this.size)
        this.tableList = this.mapChildren(this.deptList)
        this.loading = false;
      }).catch(() => {
        this.loading = false
      });
    },
    /** 递归树结构*/
    mapChildren(arr) {
      const newArr = []
      arr.forEach(item => {
        const obj = item
        if(item.children) {
          if (!item.children.length) {
            obj.hasChildren = false
          } else {
            // 保存对象children
            this.lazyTreeNodeMap[item.deptId] = this.mapChildren(item.children)
            obj.hasChildren = true
          }
          delete obj.children
        }
        newArr.push(obj)
      })
      return newArr
    },
    /* el-table懒加载调用方法,返回对象id下的children */
    getChildren(tree, treeNode, resolve) {
      resolve(this.lazyTreeNodeMap[tree.deptId] || [])
    },
  }
  // 分页
  
    handleSizeChange(size) {
      this.size = size
      const start = 0 + (this.page - 1) * this.size
      this.tableList = this.mapChildren(this.deptList).splice(start, this.size)
    },

    handleCurrentChange(page) {
      this.page = page
      const start = 0 + (this.page - 1) * this.size
      this.tableList = this.mapChildren(this.deptList).splice(start, this.size)
    },
}
     
</script>

你可能感兴趣的:(VUE开发,vue.js,前端)