vue3使用element的table树形懒加载刷新节点问题

8,193 阅读1分钟

element+树形懒加载文档

  • element文档
  • 懒加载-就第一次进行展开调用接口,重复展开不调用。
  • 删除不刷新整个列表,而是刷新当前节点。

看看效果

hXNJHWVIl8.gif

1、代码

  • template
<template>
  <div class="lazy-table">
    <el-table
        ref="lazyTableRef"
        :data="fatherList"
        style="width: 100%"
        row-key="id"
        border
        lazy
        :load="load"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column prop="id" label="Id" width="100"/>
      <el-table-column prop="name" label="Name" width="180"/>
      <el-table-column prop="age" label="age" width="180"/>
      <el-table-column
          label="操作"
          width="250"
      >
        <template #default="scope">
          <el-link type="primary" class="table-link" @click="handleDelete(scope.row)">删除</el-link>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
  • script
<script setup>
import { ref, onMounted } from 'vue'
const lazyTableRef = ref(null)
//模拟获取父list
const fatherList = ref([])
onMounted(()=>{
  setTimeout(()=>{
    fatherList.value = [
      {
        id: 1,
        name: 'A',
        age: '15',
        hasChildren: true
      },
      {
        id: 2,
        name: 'B',
        age: '16',
        hasChildren: true
      },
    ]
  }, 500)
})
//懒加载钩子函数
const load = (row, treeNode, resolve) => {
  //根据父组件的id通过接口得到子数据, 这里用setTimeout模拟
  setTimeout(() => {
    console.log(55, row.id)
    resolve([
      {
        id: row.id*10 + 1,
        name: 'child-1',
        age: '11',
        parentId: row.id
      },
      {
        id: row.id*10 + 2,
        name: 'child-2',
        age: '22',
        parentId: row.id
      },
    ])
  }, 500)
}
//删除事件
const handleDelete = (item) =>{
  const store = lazyTableRef.value.store
  //判断是父还是子
  if(item.hasOwnProperty('hasChildren')){
    //父对象删除
    console.log(74, store.states.data.value)
    const fatherList = store.states.data.value
    //删除
    const delIndex = fatherList.findIndex(i=>item.id === i.id)
    fatherList.splice(delIndex, 1)
  }else{
    //子对象删除
    const childList = store.states.lazyTreeNodeMap.value[item.parentId]
    //删除
    const delIndex = childList.findIndex(i=>item.id === i.id)
    childList.splice(delIndex, 1)
  }
}

</script>

2、删除效果

  • 添加,修改,也类似

el5dvCWY4v.gif

3、注意点

1、 由于父子列表的删除事件用的都是同一个钩子函数,我们利用hasChildren区分
2、 不同的节点,我们找到不同列表进行渲染

table对象 const lazyTableRef = ref(null)
父节点列表 const fatherList = store.states.data.value
子节点列表 const childList = store.states.lazyTreeNodeMap.value[item.parentId]