问题描述: iview的Tree组件的数据格式跟后台给的数据不一致,数据是根据id与parentid进行来进行分层级关系的,需要自己处理一下
iview的 tree 数据格式
1, 数据格式,根据id和pid进行层级关系对比,pid不存在或者为0时,说明是树的第一级
items:[
{parentId: 0, title: "服装", id: 1}
{parentId: 1, title: "衣服", id: 2}
{parentId: 1, title: "裤子", id: 3}
{parentId: 0, title: "家具", id: 4}
{parentId: 4, title: "柜子", id: 5}
]
复制代码
2, 数据处理过程(productsType是data)
- html代码
<Tree ref="tree" :data="productsType"></Tree>
复制代码
- ts处理数据代码
get productsType () {
let {productTypeList} = this.tracking // 这个就是后台拿到的数据data
// 删除所有 children,以防止多次调用(这一步是最后执行完之后加上的,因为不删除会多次调用)
productTypeList.forEach(el => {
delete el.children
})
let map = {}
productTypeList.forEach(el => {
map[el.id] = el // 循环data拿到所有的id
})
// 注:这样执行之后map大概是这样的,map{1:{}, 2:{}, 3,{}, 4:{}, 5:{}},以id为key键值
let arr = []
productTypeList.forEach(el => {
let parent = map[el.parentId] // 拿到所有的pid,如果为真,和id进行对比,如果pid===id,就说明是id的子集
// map[el.parentId] 以el.parentId去map里面找key键id
// 比如:parent就相当于 {1:{},4{}},循环出来的有pid的跟上面的id对应,说明是上面id的子集,就把这条数据给parent的children,说明是子集
这里再看一遍数据格式,找id和parentId的关系
// items:[
// {parentId: 0, title: "服装", id: 1}
// {parentId: 1, title: "衣服", id: 2}
// {parentId: 1, title: "裤子", id: 3}
// {parentId: 0, title: "家具", id: 4}
// {parentId: 4, title: "柜子", id: 5}
// ]
if (parent) {
(parent.children || (parent.children = [])).push(el)
} else { // 如果不是就是第一级,没有pid或者pid为0
arr.push(el)
console.log('arr', arr)
}
})
return arr
}
复制代码
3, 比较常规的处理数据的方法
let newData = []
function TreeData (title, id) {
this.title = title
this.id = id
}
let len = productTypeList.length
for (let i = 0; i < len; i++) {
if (productTypeList[i].parentId === 0) {
newData.push(new TreeData(productTypeList[i].name, productTypeList[i].id))
}
}
for (let j = 0; j < newData.length; j++) {
let childrenData = []
for (let m = 0; m < productTypeList.length; m++) {
if (newData[j].id === productTypeList[m].parentId) {
childrenData.push(new TreeData(productTypeList[m].name, productTypeList[m].id))
newData[j].children = childrenData
}
}
}
console.log(newData)
return newData
复制代码
-
如有问题,欢迎指正
-
本文为原创,如需转载,请注明出处:iview Tree数据格式问题,无限递归树处理数据