Implementing Single Node Selection with the el-cascader Component
Using el-cascader in Vue 3 with Element Plus
A common requirement is to bind the component's value to a single leaf node identifier rather than an array representing the full path.
Template Strcuture
<el-cascader
v-model="currentNodeId"
style="min-width: 250px;"
ref="cascaderRef"
:options="treeData"
:props="config"
clearable
collapse-tags
@change="onSelectionChange"
placeholder="Select an option">
</el-cascader>
Component Logic
// Configuration for the cascader component
const componentConfig = {
expandTrigger: 'hover',
label: 'labelName',
checkStrictly: true,
value: 'nodeId',
}
const cascaderRef = ref()
function onSelectionChange(selectedData) {
const selectedNodes = cascaderRef.value.getCheckedNodes()
currentNodeId.value = selectedNodes[0]?.value
}
Vue 2 Implementation with Element UI
To confiugre the component so its v-model binds directly to a leaf node ID, set the emitPath property to false.
<template>
<div>
<el-cascader
v-model="selectedId"
:options="treeOptions"
:props="cascaderConfig"
@change="handleSelectionChange"
clearable>
</el-cascader>
<div style="margin-top: 20px;">
Selected Node ID: {{ selectedId }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
selectedId: null,
treeOptions: [
{
id: 1,
name: 'Parent Node A',
subNodes: [
{ id: 11, name: 'Child Node A-1' },
{ id: 12, name: 'Child Node A-2' }
]
},
{
id: 2,
name: 'Parent Node B',
subNodes: [
{ id: 21, name: 'Child Node B-1' },
{ id: 22, name: 'Child Node B-2' }
]
}
],
cascaderConfig: {
value: 'id',
label: 'name',
children: 'subNodes',
emitPath: false
}
}
},
methods: {
handleSelectionChange(nodeId) {
console.log('Selected node identifier:', nodeId)
this.selectedId = nodeId
}
}
}
</script>
Lazy Loading Data Dynamically
For large datasets, implement on-demand loading of child nodes.
<el-cascader
v-model="selectedNodeId"
:options="lazyOptions"
:props="{
value: 'id',
label: 'label',
children: 'children',
emitPath: false,
lazy: true,
lazyLoad: loadChildNodes
}">
</el-cascader>
methods: {
loadChildNodes(node, callback) {
const parentNodeId = node.value
fetchChildren(parentNodeId).then(response => {
callback(response.data)
})
}
}