Bootstrap

Vue+Element中Table树形数据懒加载新增(删除 编辑同理)后数据动态更新

请添加图片描述

<template>
  <div>
    <div>
      <el-button type="primary" @click="addTo">添加</el-button>
    </div>
    
    <el-table ref="table" :data="tunnelList" row-key="id" lazy :load="load" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" border>
      <el-table-column label="序号" width="55" align="center">
        <template slot-scope="scope">{{ scope.$index + 1 }}</template>
      </el-table-column>
      <el-table-column prop="name" label="名称" align="center"></el-table-column>
      <el-table-column prop="date" label="时间" align="center"></el-table-column>
      <el-table-column prop="address" label="地址" align="center"></el-table-column>
    </el-table>
  </div>
</template>

<script>
export default {
  name: '',
  components: {},
  props: {},
  data() {
    return {
      tunnelList: [
        {
          id: 1,
          date: '2016-05-02',
          name: '王小虎',
          address: '上海市普陀区金沙江路 1518 弄'
        }, {
          id: 2,
          date: '2016-05-04',
          name: '王小虎',
          address: '上海市普陀区金沙江路 1517 弄'
        }, {
          id: 3,
          date: '2016-05-01',
          name: '王小虎',
          address: '上海市普陀区金沙江路 1519 弄',
          hasChildren: true
        }
      ],
      tId: '',
      loadData: new Map(),
    }
  },
  filters: {},
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  beforeDestroy() {},
  methods: {
    getSonData(id, resolve, addData) { // 模拟调用接口
      let data = [
        {
          id: 31,
          date: '2016-05-01',
          name: '王小虎',
          address: '上海市普陀区金沙江路 1519 弄'
        }, {
          id: 32,
          date: '2016-05-01',
          name: '王小虎',
          address: '上海市普陀区金沙江路 1519 弄'
        }
      ]
      
      if (addData) {
        data.push(addData)
      }

      setTimeout(() => {
        resolve(data)
      }, 1000)
    },
    load(tree, treeNode, resolve) {
      this.tId = tree.id // 储存当前展开节点
      this.loadData.set(this.tId, { tree, treeNode, resolve }) // 缓存load
      this.getSonData(tree.id, resolve) // 重置子节点数据
    },
    addTo() {
      let id = this.tId
      const { tree, treeNode, resolve } = this.loadData.get(id); // 根据id取出对应节点的数据
      this.$set(this.$refs.table.store.states.lazyTreeNodeMap, id, []); // 重置当前对应id的节点
      let addData = { // 模拟新增数据
        id: 33,
        date: '2016-05-01',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1519 弄'
      }
      this.getSonData(tree.id, resolve, addData) // 重置子节点数据
    }
  }
}
</script>

<style scoped lang="less">
</style>

;