需求:需要将平铺结构转换成树形结构
1.在utils里面封装函数
export function transfromListToTree(arr, pid) {
const list = []
arr.forEach((item) => {
if (item.pid === pid) {
const tmp = transfromListToTree(arr, item.id)
if (tmp.length > 0) {
item.children = tmp
}
// 如果循环的每一个元素的 pid 和传进来的 id相等,就找到了父元素,进入到新数组
list.push(item)
}
})
return list
}
2.在main.js里面挂载
import { arrToTree } from '@/utils/arr-to-tree'
Vue.prototype.arrToTree = arrToTree
3. this.permissionList = transfromListToTree(res.data, 0) 将数组和pid传入函数里面