vue3+element-plus组件下拉列表,数组数据转成树形数据

引入组件

可以直接在项目中引入element-plus表格组件,如果需要变成下拉列表样式需要添加以下属性:

row-key 必填 最好给数字或唯一属性 , 给每个节点设置id 不填的话 没有办法实现展开效果

load 这个是动态添加数据的 前提(开启lazy ,表格数组里设置了hasChildren:true)

treeprops 是配置树状收缩数据的

treeprops :{hasChildren} 是否可收缩

treeprops :{children} 展开的子项

代码示例:

复制代码
 <el-table
        :data="
         (所需要的渲染数据)
        "
        row-key="id"
        style="width: 100%; border: 0.1px solid #ebeef5"
        v-loading="loading"
        lazy
        :load="load"
        :tree-props="{ hasChildren: 'hasChildren', children: 'children' }"//
      >

普通数组转换成树形数据

复制代码
 const transListDataToTreeData = (list, root) => {
      console.log(list);
      const arr = [];
      // 1.遍历
      list.forEach(item => {
        // 2.首次传入空字符串  判断list的pid是否为0 如果为空就是一级节点
        if (item.pid === root) {
          // 找到之后就要去找item下面有没有子节点  以 item.id 作为 父 id, 接着往下找
          const children = transListDataToTreeData(list, item.id);
          if (children.length > 0) {
            // 如果children的长度大于0,说明找到了子节点
            item.children = children;
          }
          // 将item项, 追加到arr数组中
          arr.push(item);
          console.log(arr);
          console.log(arr);
        }
      });
      return arr;
    };
  transListDataToTreeData(初始数组, "");
相关推荐
FYKJ_20101 小时前
springboot校园兼职平台--附源码02041
java·javascript·spring boot·python·eclipse·django·php
用户6688599847665 小时前
Vue 3.0安装与使用
vue.js
空中海6 小时前
01 React Native 基础、核心组件与布局体系
javascript·react native·react.js
前端之虎陈随易8 小时前
2年没用Nodejs了,Bun很香
linux·前端·javascript·vue.js·typescript
好运的阿财9 小时前
OpenClaw工具拆解之host_workspace_write+host_workspace_edit
前端·javascript·人工智能·机器学习·ai编程·openclaw·openclaw工具
XiYang-DING9 小时前
JavaScript
开发语言·javascript·ecmascript
空中海10 小时前
02 React Native状态、导航、数据流与设备能力
javascript·react native·react.js
空中海11 小时前
02 状态、Hooks、副作用与数据流
开发语言·javascript·ecmascript
abcnull11 小时前
传统的JavaWeb项目Demo快速学习!
java·servlet·elementui·vue·javaweb
空中海11 小时前
04 React Native工程化、质量、发布与生态选型
javascript·react native·react.js