The requirement involves creating an el-tree component where root nodes cannot be selected and child nodes allow single selection only.
Implementation Code:
<template>
<el-tree
:data="treeData"
show-checkbox
node-key="identifier"
:check-strictly="true"
@check="onNodeSelection"
ref="treeRef"
>
</el-tree>
</template>
Property Descriptions:
show-checkbox: Displays selection checkboxescheck-strictly: Disables parent-child relationship binding@check: Event triggered when clicking on nodes
<script>
import { ref } from 'vue';
export default {
setup() {
const treeRef = ref(null);
const treeData = ref([
{
identifier: 5,
label: 'Root Level',
children: [
{ identifier: 6, label: 'Child Item A' },
{ identifier: 7, label: 'Child Item B' }
]
}
]);
const onNodeSelection = (selectedNode, selectionInfo) => {
// Prevent selection of root level nodes
if (selectedNode.identifier === 5) {
treeRef.value.setCheckedKeys([]);
return;
}
// Retrieve currently selected keys
const currentSelections = treeRef.value.getCheckedKeys();
// Handle multiple selections by keeping only the latest
if (currentSelections.length > 1) {
const conflictingSelections = currentSelections.filter(key => key !== selectedNode.identifier);
// Update to keep only the current selection
treeRef.value.setCheckedKeys([selectedNode.identifier]);
// Deselect previously selected items
conflictingSelections.forEach(key => {
treeRef.value.setChecked(key, false);
});
// Ensure current selection remains active
treeRef.value.setChecked(selectedNode.identifier, true);
}
};
return {
treeData,
onNodeSelection,
treeRef
};
}
};
</script>
Implementation Logic:
The solution primarily utilizes the check event handler for control:
First, verify whether the current node represents a root node. In this example, nodes with identifier equal to 5 are treated as root nodes - adjust according to your specific root identification logic. When a root node is selected, use the setCheckedKeys method through the reference object to clear all selections.
For non-root node selections, the first selection requires no special handling. However, when a second selection occurs, filter out the previously selected node identifiers based on the currently selected node's ID. Set the checked property of previously selected node IDs to false, effectively removing their selection status. Simultaneously, ensure the currant node's checked property is set to true.