处理ElementUI中Cascader级联选择器控件v-model属性为所选项路径数组, 1:cascaderTree([],string,string) 类构造器,用于构造一次转换,传入要转换的数组,数据主键名,父数据主键名 2:cascaderTree.prototype.init(); 实例函数,用户将数据按配置初始化,形成树状结构的数据
/***
* @author: mistywood
* @date:20200402
* @description:
* 处理ElementUI中Cascader级联选择器控件v-model属性为所选项路径数组,
* 1:cascaderTree([],string,string) 类构造器,用于构造一次转换,传入要转换的数组,数据主键名,父数据主键名
* 2:cascaderTree.prototype.init(); 实例函数,用户将数据按配置初始化,形成树状结构的数据,并存在
*
* @example:
* let data = new cascaderTree(data,"id","pid").init();
*
* @interface:
* cascaderTree.prototype.init()
*/
export default class cascaderTree{
constructor (a, idKey, pIdKey){
this.tree = a || [];
this.idKey = idKey || "id";
this.pIdKey = pIdKey || "pId";
this.groups = {};
this.ids = {};
this.rootIds = [];
}
init() {
this.group();
let result = [];
for (let i = 0; i < this.rootIds.length; i++) {
let item = this.rootIds[i];
let children = this.getChilds(this.groups[this.rootIds[i][this.idKey]]);
if (children !== undefined && children.length > 0) {
item.children = children;
}
result.push(item);
}
return result;
}
group() {
for (let i = 0; i < this.tree.length; i++) {
delete this.tree[i].children;// 删除多余children(空值)
if (this.groups[this.tree[i][this.pIdKey]] === undefined) {
this.groups[this.tree[i][this.pIdKey]] = [];
}
this.groups[this.tree[i][this.pIdKey]].push(this.tree[i]);
if (this.ids[this.tree[i][this.idKey]] === undefined) {
this.ids[this.tree[i][this.idKey]] = this.tree[i];
}
}
for (let i = 0; i < this.tree.length; i++) {
if (this.ids[this.tree[i][this.pIdKey]] === undefined) {
this.rootIds.push(this.tree[i]);
}
}
}
getChilds(a) {
if (!a) {
return undefined;
}
let list = [];
for (let i = 0; i < a.length; i++) {
let o = a[i];
let children = this.getChilds(this.groups[a[i][this.idKey]]);
if (children && children.length > 0) {
o.children = children;
}
list.push(o);
}
return list;
}
}
实例:
文件命名为 cascaderTree.js目录结构如下
demo内代码如下
<template>
<div>
<el-tree :data="treeData" :props="defaultProps"></el-tree>
</div>
</template>
<script>
import cascaderTree from "@/lib/cascaderTree.js";
export default {
data() {
return {
data: [
{
"id": "1",
"name": "1",
"pid": "0",
},
{
"id": "2",
"name": "1-1",
"pid": "1",
},{
"id": "3",
"name": "1-1-1",
"pid": "2",
},
{
"id": "4",
"name": "1-1-2",
"pid": "2",
},
{
"id": "5",
"name": "2",
"pid": "0",
},
{
"id": "6",
"name": "2-1",
"pid": "5",
},
{
"id": "7",
"name": "2-2",
"pid": "5",
},
],
treeData:[],
defaultProps: {
id:'id',
label: 'name'
}
};
},
mounted() {
this.treeData=new cascaderTree(this.data,'id','pid').init();
console.log(this.treeData)
}
};
</script>