处理扁平化数组数据为树状结构,以便用于ElementUI中Cascader级联选择器控件绑定数据

处理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目录结构如下

处理扁平化数组数据为树状结构,以便用于ElementUI中Cascader级联选择器控件绑定数据_第1张图片

demo内代码如下




 

你可能感兴趣的:(vue+ElementUI学习)