el-tree实现懒加载

时间:2024-04-09 21:15:25

 一、懒加载树结构

<div class="hello" id="container">
    <el-tree
      ref="tree"
      node-key="id"
      :default-expanded-keys="[2]"
      current-node-key="2"
      :props="defaultProps"
      :check-strictly="true"
      @node-click="getChecked"
      @check="handleCheck"
      highlight-current
      :load="loadNode"
      lazy
    >
    </el-tree>
 </div>

data() {
   defaultProps: {
      // children: 'children',
      label: 'label',
       isLeaf: 'leaf'
    }
},
methods: {
    loadNode(node, resolve) {
      console.log('level:=====', node.level)
      if (node.level === 0) {
        return resolve([
          { id: 1, label: 'region' },
          { id: 2, label: 'region2' }
        ])
      }
      if (node.level > 1) return resolve([])

      setTimeout(() => {
        const data = [
          {
            id: 3,
            label: '一级 3',
            leaf: true
          },
          {
            id: 4,
            label: 'zone'
          }
        ]

        resolve(data)
      }, 500)
    }
}

二、懒加载并做数据回显

<el-tree
      ref="tree"
      node-key="id"
      current-node-key="2"
      :props="defaultProps"
      :check-strictly="true"
      :show-checkbox="showCheckbox"
      :default-expanded-keys="allSelectOptions"  
      :default-checked-keys="remainIds"
      @node-click="getChecked"
      @check="handleCheck"
      highlight-current
      :load="loadNode"
      lazy
    >
 </el-tree>
// allSelectOptions--默认展开节点得key数组
// remainIds--默认选中key
// 1、defaultExpandAll 不可设置为默认展开,根据回显时,设置的default-expanded-keys?,
// 若设置默认展开值,则只加载第一次,剩下走el-tree自带的懒加载;
// 若未设置展开值,则首次需要全加载出来
data() {
    return {
      defaultProps: {
        // children: 'children',
        label: 'label',
        isLeaf: 'leaf'
      },
      remainIds: [3],
      allSelectOptions: [1]
    }
  }