<el-tree
ref="treesRef"
style="max-width: 600px"
:data="dataTree"
node-key="id"
:props="defaultProps"
show-checkbox
expand-on-click-node
default-expand-all
:highlight-current="true"
@check-change="handleClick"
/>
</div>
let checkID = ref<any[]>([]);
let array = ref<any[]>([]);
const handleClick = (node: any, isCheck: any) => {
if (isCheck) {
array.value = collectIds(node);
checkID.value = checkID.value.concat(array.value);
} else {
removeIds(node, checkID.value);
}
emit("nodeClicked", checkID);
};
///获取父子id
interface TreeNode {
id: string;
children?: TreeNode[];
}
function collectIds(node: TreeNode, ids: string[] = []): string[] {
ids.push(node.id);
if (node.children) {
for (const child of node.children) {
collectIds(child, ids);
}
}
return ids;
}
/// 删除父子id
function removeIds(node: TreeNode, idToRemove: string[] = []): void {
// 如果当前节点有子节点,则递归遍历子节点
if (node.children) {
for (let i = 0; i < node.children.length; i++) {
removeIds(node.children[i], idToRemove);
// 如果子节点已经被删除,则从数组中移除
if (!node.children[i].id) {
node.children.splice(i, 1);
i--; // 减少索引以避免跳过下一个节点
}
}
} else {
idToRemove.forEach((item, i) => {
if (item == node.id) {
idToRemove.splice(i, 1);
}
});
}
}
check-Change 会在你取消勾选的时候多次触发,你选了最子集勾选掉,导致他的父亲变成了半选状态,所以再次触发了check-Change事件,导致会多删你的元素。你可以换成check事件,当然与之相对应你的代码逻辑也需要调整。
参考el-tree
或者你可以在change的时候调取api,拿到当前选中的节点。
allSelect = this.$refs.tree.getCheckedNodes()
halfSelect = this.$refs.tree.getHalfCheckedNodes()
allSelect.unshift.apply(allSelect, halfSelect)