[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
第一种:递归实现数组转为树形结构
第一步: // 递归: 封装一个函数:将列表list数据转换成数据树形数据=>递归 // 遍历树形 有一个重点 要先找一个头 function
transListDataToTreeData(list, root) { const arr = [] // 1.遍历
list.forEach((item) => { // 2.首次传入空字符串 判断list的pid是否为空 如果为空就是一级节点 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) } }) return arr } //第二步: // 调用转化方法,转化树形结构 赋值给data中定义的数组
this.departs = transListDataToTreeData(data.depts, '') //第三步: 渲染到页面 <!--
树形控件el-tree :data:指定数据 props:属性成员配置项 default-expand-all 控制是否默认展开--> <!--
el-tree组件 里面内容是插槽内容 有多少个节点循环多少次 --> <el-tree :data="departs"
:props="defaultProps" :default-expand-all="true" > </el-tree>
第二种:下载三方插件 使用arrayTotree插件 将扁平化数组转换为树形结构数组 并赋值给list
* npm install array-to-tree --save
* import arrayToTree from 'array-to-tree'
* data中的自定义数组 = arrayToTree(获取请求的数组, { parentProperty: '父级id', customID:
'二级id'});
数组扁平化:
arr = [[{},{}],[{},{}],[{},{}]] const = data = [].concat(...arr.map((v) => v))
log(data) // [{…}, {…}, {…}, {…},...] const deepFlatten = arr =>
[].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v)));
deepFlatten([1, [2], [[3], 4], 5]); // [1,2,3,4,5]