el-tree-select多选且父子互斥
时间: 2025-06-01 21:59:52 浏览: 20
### 实现 el-tree-select 多选父子互斥选择行为
在使用 `el-tree-select` 组件时,可以通过自定义逻辑来实现多选且父子节点互斥的选择行为。以下是一个完整的解决方案:
1. **配置组件属性**
需要设置 `check-strictly` 属性为 `true`,以确保父子节点之间的选择状态互不关联[^3]。
2. **监听节点变化事件**
使用 `@check-change` 事件监听节点的选中或取消状态,并根据当前节点的状态动态调整其他节点的选择状态[^3]。
3. **实现逻辑互斥**
- 如果新点击的是父节点,则需要删除该父节点下所有子节点的选中状态。
- 如果新点击的是子节点,则需要判断其父节点是否已被选中。如果父节点已选中,则取消父节点的选中状态[^1]。
以下是具体代码实现:
```vue
<template>
<el-tree-select
v-model="selectedKeys"
:data="treeData"
multiple
check-strictly
@check-change="handleCheckChange"
/>
</template>
<script>
export default {
data() {
return {
selectedKeys: [], // 当前选中的节点
treeData: [
{
id: 1,
label: "父节点1",
children: [
{ id: 11, label: "子节点1-1" },
{ id: 12, label: "子节点1-2" },
],
},
{
id: 2,
label: "父节点2",
children: [
{ id: 21, label: "子节点2-1" },
{ id: 22, label: "子节点2-2" },
],
},
],
};
},
methods: {
handleCheckChange(node, checked) {
if (checked) {
// 如果选中的是父节点,清除其子节点的选中状态
if (node.children && node.children.length > 0) {
this.clearChildrenSelection(node);
} else {
// 如果选中的是子节点,检查父节点是否被选中并清除父节点的选中状态
const parentNode = this.findParentNode(this.treeData, node);
if (parentNode && this.selectedKeys.includes(parentNode.id)) {
this.removeSelection(parentNode.id);
}
}
} else {
// 如果取消选中的是子节点,检查父节点是否还有其他子节点被选中
const parentNode = this.findParentNode(this.treeData, node);
if (parentNode) {
this.checkParentSelection(parentNode);
}
}
},
clearChildrenSelection(node) {
node.children.forEach((child) => {
if (this.selectedKeys.includes(child.id)) {
this.removeSelection(child.id);
}
});
},
removeSelection(id) {
this.selectedKeys = this.selectedKeys.filter((key) => key !== id);
},
findParentNode(tree, node) {
for (const parent of tree) {
if (parent.children && parent.children.some((child) => child.id === node.id)) {
return parent;
}
if (parent.children) {
const result = this.findParentNode(parent.children, node);
if (result) return result;
}
}
return null;
},
checkParentSelection(parentNode) {
const allChildrenSelected = parentNode.children.every((child) =>
this.selectedKeys.includes(child.id)
);
if (allChildrenSelected && !this.selectedKeys.includes(parentNode.id)) {
this.selectedKeys.push(parentNode.id);
} else if (!allChildrenSelected && this.selectedKeys.includes(parentNode.id)) {
this.removeSelection(parentNode.id);
}
},
},
};
</script>
```
### 说明
- `clearChildrenSelection` 方法用于清除父节点下的所有子节点选中状态[^1]。
- `findParentNode` 方法用于递归查找指定子节点的父节点。
- `checkParentSelection` 方法用于检查父节点是否应该被选中或取消选中。
###
阅读全文
相关推荐


















