<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: [
// 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];
// console.log(allPaths);
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 pathInChild;/
}
}
}
return allPaths;
},
},
mounted() {
const targetId = '3'; // 替换为你要选中的相同id
this.highlightPaths(targetId);
// this.renderFormat()
console.log(this.findPath(this.options,targetId))
}
};
</script>
<style>
.highlight {
background-color: red !important;
}
</style>
递归处理,级联最后一级有重复id还显示所有路径高亮
最新推荐文章于 2024-07-08 15:54:08 发布
本文介绍了如何在Vue应用中使用el-cascader组件构建一个多级选项的级联选择器,并展示了如何实现在特定选项被选中时进行动态高亮以及查找路径的功能。
摘要由CSDN通过智能技术生成