公司服务升级确定了新的架构,假如当前部门是二级部门,二级部门下的三级部门全部已选择,那么后端接口要求只需要传二级部门的id,并且操作符传参为 like;如果某一个部门已选择,切父级部门没有选择,那么就需要传参为具体子部门的id,操作符为 in
① 只要所选部门中包含一个或一个以上的父级部门(父级部门标识 isParent 为true),
传参:将属于该父级部门中的子级部门全部去除,并保留该父级部门
操作符: like
② 只要所选部门中不包含任何一个父级部门(父级部门标识 isParent 为true),
传参: 所有已选部门的id
操作符: in
这个之前我翻了好多的elementUI tree的文档,都没有找到合适的解决方案,上次看到了一个解决方法,但是对性能不是很好,所以我优化了一下
思路: 可以使用 getCheckedNodes() 获取到所有已选的数据(包括所有的父子部门),根据父部门的特点isParent === true 来去除所有的父级部门,并且树绑定的treePos,是有特殊规律的,根据当前树的层级来的
解决方案一:
let treeNodes = this.$refs.tree.getCheckedNodes()
let treeKeys = this.$refs.tree.getCheckedKeys()
this.checkPos = []
this.operatorType = this.scope.dataScope.operatorType || 'like'
let parentNodes = treeNodes.filter((item) => {
return item.isParent === true
})
if (parentNodes.length !== 0) {
let parentPos = parentNodes.map(it => {
return it.treePos
})
this.operatorType = 'like'
this.checkPos = treeKeys.filter(elem => {
let isBottom = parentPos.every((el) => {
return elem.includes(el) && elem !== el
})
if (!isBottom) {
return elem
}
})
} else {
this.operatorType = 'in'
this.checkPos = treeKeys
}
解决方案二:循环遍历树结构,找到上一级或者最后一级已选中的data
findParents(store) {
const checkedNodes = [];
const filterNodes = function(node) {
const treeNodes = node.root ? node.root.childNodes : node.childNodes;
treeNodes.forEach(child => {
if (child.checked) { // 已找到选中的上一级或者当前最后一级
checkedNodes.push(child);
}
if (child.indeterminate) { // 节点的子树中是否有被选中的节点
filterNodes(child);
}
});
};
filterNodes(store)
return checkedNodes;
}
findParents(this.$refs.tree.store) // 输出树数据