el-table異步樹形表格與數據懶加載


樹形表格數據過多時,可以使用懶加載方式獲取子級數據

 
完成效果: 先加載出父級數據, 點擊折疊按鈕請求子級數據
  

 

代碼實現: index.vue
<template>
  <div>
    <el-table
      :data="tableData"
      style="width: 100%;margin-bottom: 20px;"
      row-key="id"
      border
      default-expand-all
      lazy :load="loadData"
      :tree-props="{hasChildren: 'hasChildren'}">
      <el-table-column
        prop="date"
        label="日期"
        width="180">
      </el-table-column>
      <el-table-column
        prop="name"
        label="姓名"
        width="180">
      </el-table-column>
      <el-table-column
        prop="address"
        label="地址">
      </el-table-column>
      <el-table-column label="操作" width="80">
        <template slot-scope="scope">
          <el-button
            size="mini"
            >詳情</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { getTableData } from '@/service/list'

export default {
  data () {
    return {
      tableData: []
    }
  },

  created() {
    this.getData()
  },

  methods: {
    // 獲取表格數據
    async getData () {
      const { data } = await getTableData()
      this.tableData = data.map((item, i) => {
        if (i === 2) {
          return {
            ...item,
            hasChildren: false
          }
        }
        return {
          ...item,
          hasChildren: true // 設置true就有折疊圖標
        }
      })
    },

    // 獲取子級數據
    loadData (row, treeNode, resolve) {
      console.log(row, treeNode)
      getTableData({id: row.id, level: row.level}).then(res => {
        // 懶加載延時效果
        // setTimeout(() => {
        //   resolve(res.data)
        // }, 1000)
        resolve(res.data.map((item, i) => {
          if (i === 1 && row.level < 4) {
            return {
              ...item,
              hasChildren: true
            }
          }
          return item
        }))
      })
    }
  }
}
</script>

 

其他和普通表格一樣使用,主要注意這三個屬性

 

1. lazy在懶加載中必須設置
2. load子級數據獲取方法, 通過resolve返回數據
3. tree-props 懶加載樹形數據需要設置hasChildren, 父級數據如果是true,就有展開圖標, false就沒有展開圖標 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM