以vue+TreeSelect为例,如何将扁平数据转为tree形数据
// 目标:将后台返回的扁平数据,根据parentId转为下拉tree
<el-form-item label='下拉选择数据'>
<tree-select
v-model='treeVlue'
:options='myTreeList'
:props="{ label:'treedataname' value:'treedataid' children:'childList'}"
/>
</el-form-item>
//
export default{
data(){
myTreeList:[],
treeValue:'',
initData:[
{treedataid: 503,treedataname: "心脏内科",lngparentid: 0};
{treedataid: 504,treedataname: "心脏内科一科",lngparentid: 503};
{treedataid: 506,treedataname: "胸痛门诊",lngparentid: 504};
{treedataid: 507,treedataname: "神经内科",lngparentid: 0};
{treedataid: 508,treedataname: "神经内科一病区",lngparentid: 507};
] //假设initData为待处理的扁平化数据,数据结构如上,其中lngparentid为0表示第一级,为其他数表示子级。应用中也可以是后台返回的数据
},
methods:{
getTreeData(){
//深度拷贝数据,防止影响原数据
this.myTreeList=JSON.parse(JSON.stringfy(this.initData))
//两层过滤
this.myTreeList.filter(father => {
const branchArr=this.myTreeList.filter(child => father.treedataid===child.lngparentid) //返回每一项的子级数组
branchArr.length>0?father.childList=branchArr:father.childList=[]
return father.lngparentid===0 //返回第一层
})
//将lngparentid不是0的删掉
this.myTreeList=this.myTreeList.filter(e=>{
return e.lngparentid === 0
})
}
}
}