前言:vue开发项目时用到了element-ui的树组件,但是发现一执行过滤事件,树就全部都展开了,为了解决这个问题,只能自己先过滤数剧,再赋值给树组件的data,就避免了一上来全部展开的尴尬。

一、简单版本

         data() {
return {
shopsData: [],
arrData: [{
label: '一级 1',
children: [{
label: '二级 1-1',
children: [{
label: '三级 1-1-1'
}]
}]
}, {
label: '一级 2',
children: [{
label: '二级 2-1',
children: [{
label: '三级 2-1-1'
}]
}, {
label: '二级 2-2',
children: [{
label: '三级 2-2-1'
}]
}]
}, {
label: '一级 3',
children: [{
label: '二级 3-1',
children: [{
label: '三级 3-1-1'
}]
}, {
label: '二级 3-2',
children: [{
label: '三级 3-2-1'
}]
}]
}]
}
},
methods: {
filterByName(menu, type, name) { //过滤树组件
var menuNew = [];
for (var i = 0; i < menu.length; i++) {
var nodeNew = undefined;
var node = menu[i]; //同级的每一个根节点
var childrenNode = node.children; //子节点
var childrenMenu = []; if (childrenNode) {
if (childrenNode.length > 0) { //子节点下面的子节点递归
childrenMenu = this.filterByName(childrenNode, type, name);
}
} if (childrenMenu) {
if (childrenMenu.length > 0) {
nodeNew = new Object();
nodeNew = this.nodeFillNewFromOld(node, nodeNew);
nodeNew.sublist = childrenMenu; //复制子节点
} else {
if (this.checkNodeEquals(node, type, name)) {
nodeNew = new Object();
nodeNew = this.nodeFillNewFromOld(node, nodeNew);
}
}
}
if (nodeNew) {
menuNew.push(nodeNew);
}
} return menuNew;
},
nodeFillNewFromOld(oldNode, newNode) { //添加属性
newNode.disabled = oldNode.disabled;
newNode.enabled = oldNode.enabled;
newNode.level = oldNode.level;
newNode.name = oldNode.name;
newNode.onlyHasShop = oldNode.onlyHasShop;
newNode.orgType = oldNode.orgType;
newNode.orgcode = oldNode.orgcode;
newNode.parentCode = oldNode.parentCode;
newNode.prmType = oldNode.prmType;
newNode.showPage = oldNode.showPage;
newNode.children = oldNode.children; return newNode;
},
checkNodeEquals(node, type, name) { //过滤条件
if (node.type === 2) {
node.disabled = true
}
if (node.orgcode.indexOf(name) === 0) {
return true;
} else {
return false;
}
}
},
mounted() {
this.shopsData = this.filterByName(this.arrData, 'label', '二级 2-1');
}

二、升级版本

         filterTree(nodes, predicate, childKey = 'children') { //predicate过滤条件函数
if (!nodes || !nodes.length) return void 0
const children = []
for (let node of nodes) {
node = Object.assign({}, node)
const sub = this.filterTree(node[childKey], predicate, childKey)
if ((sub && sub.length) || predicate(node)) {
sub && (node[childKey] = sub)
children.push(node)
}
}
return children.length ? children : void 0
},
shopfilterNode(data) { //过滤条件
if (data.orgType === 2) {
data.disabled = true
}
return data.prmType >= 0 && data.orgcode.indexOf(this.groupcode) === 0;
},
mounted() {
this.shopsData = this.filterTree(this.arrData, this.shopfilterNode, 'sublist')
}
 
04-13 01:20