<template>
<el-cascader
v-model="selectedOptions"
:options="options"
:props="props"
@change="change"
>
<template slot-scope="{ node, data }">
<span :class="{ 'highlight': node.highlight }">{{ node.label }}</span>
</template>
</el-cascader>
</template>
<script>
export default {
data() {
return {
selectedOptions: ['3'],
options: [
{
value: '1',
label: 'Option 1',
children: [
{
value: '2',
label: 'Option 2',
children: [
{
value: '3',
label: 'Option 3',
},
{
value: '4',
label: 'Option 4',
}
]
},
{
value: '5',
label: 'Option 4',
children: [
{
value: '3',
label: 'Option 3',
},
{
value: '4',
label: 'Option 4',
}
]
}
]
},
],
props: {
value: 'value',
label: 'label',
children: 'children',
emitPath:false
}
};
},
methods: {
change(val){
console.log(val);
},
renderFormat(labels) {
return labels.join(' / ');
},
highlightPaths(id) {
this.options.forEach(option => {
this.traverseAndHighlight(option, id);
});
},
traverseAndHighlight(node, id) {
if (node.value === id) {
node.highlight = true;
} else {
node.highlight = false;
}
if (node.children && node.children.length > 0) {
node.children.forEach(child => {
this.traverseAndHighlight(child, id);
});
}
},
findPath(options,targetId, currentPath = []) {
const allPaths = [];
for (const node of options) {
console.log(node,'node');
const newPath = [...currentPath, node.value];
if (node.value === targetId) {
return newPath;
}
if (node.children && node.children.length > 0) {
const pathInChild = this.findPath(node.children, targetId, newPath);
console.log(pathInChild,'pathInChild');
if (pathInChild) {
allPaths.push(pathInChild);
}
}
}
return allPaths;
},
},
mounted() {
const targetId = '3';
this.highlightPaths(targetId);
console.log(this.findPath(this.options,targetId))
}
};
</script>
<style>
.highlight {
background-color: red !important;
}
</style>