解决el-tree数据回显时子节点部分选中父节点都全选中问题
//数据结构
<el-tree ref="tree_edit" :check-strictly="checkStrictly" :data="powerList" :props="defaultProps" :default-expand-all="true" :default-expanded-keys="checkedCities" :default-checked-keys="checkedCities" @check-change="handleClick_edit" show-checkbox node-key="id" class="permission-tree" />
powerList: [], //数组
checkList_edit: [],//修改勾选
checkStrictly: false,
defaultProps: {
children: 'children',
label: 'menuName',
},
编辑回显方法(匹配选中id,接口返回选中id数组)设置选中:
edit(index) {
this.dialogFormVisible_edit = true;
this.checkStrictly = true; //重点:给数节点赋值之前 先设置为true
let menuIds = Array.from(new Set(this.tableData[index].menuButtonIds.split(",")));
let intArray = menuIds.map(str => parseInt(str));
console.log(intArray);
API.GetMenu({}).then(res => {
if (res.code == 200) {
this.roleform_edit.id = this.tableData[index].id;
this.roleform_edit.status = this.tableData[index].status;
this.roleform_edit.roleName = this.tableData[index].roleName;
this.roleform_edit.remark = this.tableData[index].remark;
this.$nextTick(() => {
this.powerList = res.data;
this.checkedCities = intArray;//回显
this.$refs.tree_edit.setCheckedKeys(intArray, true)
this.checkStrictly = false //重点: 赋值完成后 设置为false
})
//简单方法
/*this.$nextTick(() => {
let arr=[];
this.powerList.forEach(item=>{
if(!this.$refs.tree_edit.getNode(item.id).childNodes || !this.$refs.tree_edit.getNode(item.id).childNodes.length){
arr.push(item.id)
}
})
this.$refs.tree_edit.setCheckedKeys(arr);
})*/
} else {
return false;
}
})
},
再次勾选方法(以原数据结构获取选中数据):
handleClick_edit(data, checked, node) {
if (checked) {
let childNode = this.$refs.tree_edit.getCheckedKeys();//返回选中子节点的key
let parentNode = this.$refs.tree_edit.getHalfCheckedKeys();//返回选中父节点的key
let checkedAll = childNode.concat(parentNode);
this.checkList_edit = this.treeFilter(this.powerList, node => checkedAll.includes(node.id))
console.log(this.checkList_edit)
}
},
//递归匹配
treeFilter(tree, func) {
return tree.map(node => ({ ...node })).filter(node => {
node.children = node.children && this.treeFilter(node.children, func)
return func(node) || (node.children && node.children.length)
})
},