Vue实战(三):实现树形表格

Vue实战(三):实现树形表格

一、实现过程

1、布局

<template>
  <div>
    <el-row>
      <el-col :span="24">
        <span style="text-align: center">实现树形表格</span>
      </el-col>
    </el-row>
    <hr />
    <el-row>
      <el-col :span="24">
        <el-table
          :data="dataList"
          border
          width="100%"
          :header-cell-style="{ 'text-align': 'center' }"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          :row-key="(record) => record.id"
        >
          <el-table-column
            label="菜单ID"
            prop="id"
            align="center"
          ></el-table-column>
          <el-table-column label="上级菜单ID" align="center">
            <template slot-scope="scope">
              {{ scope.row.parent_id == null ? "-" : scope.row.parent_id }}
            </template>
          </el-table-column>
          <el-table-column
            label="菜单名称"
            prop="name"
            align="center"
          ></el-table-column>
        </el-table>
      </el-col>
    </el-row>
  </div>
</template>

2、转换为结构树数据

//获取结构树
    getTrees(list, parent_id = 0) {
      let parentObj = {};
      list.forEach((o) => {
        parentObj[o.id] = o;
      });
      if (!parent_id) {
        return list
          .filter((o) => !parentObj[o.parent_id])
          .map((o) => ((o.children = this.getTrees(list, o.id)), o));
      } else {
        return list
          .filter((o) => o.parent_id == parent_id)
          .map((o) => ((o.children = this.getTrees(list, o.id)), o));
      }
    },

3、初始化

//初始化数据
    getData() {
      var data = [
        { id: 1, name: "一级菜单1" },
        { id: 2, parent_id: 1, name: "二级菜单1-1" },
        { id: 3, parent_id: 1, name: "二级菜单1-2" },
        { id: 4, name: "二级菜单2" },
        { id: 5, parent_id: 4, name: "二级菜单2-1" },
        { id: 6, parent_id: 4, name: "二级菜单2-2" },
      ];
      this.dataList = this.getTrees(data);
      console.log(this.dataList);
    },

二、实现效果

折叠效果:
在这里插入图片描述

展开效果:
在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值