前言
Cascader 级联选择器和Select 选择器不同,级联选择器绑定的是id的路径
例如:
javascript
let arr=[
{id:1,label:'班级1',children:[{id:12,label:'学生12'},{id:13,label:'学生13'}]},
{id:2,label:'班级2',children:[{id:14,label:'学生14'}]}
]
Cascader 级联选择器:选中学生13绑定的值为[1,13]
Select 选择器:选中学生13绑定的值为13
因此,如果我们只知道绑定值的情况下,想让Cascader 级联选择器选中对应选项,需要遍历知道路径
遍历获取id的路径
targetId传绑定值,nodes传数组,调用后即可获得id的路径
javascript
function findNodePathById(targetId, nodes, path = []) {
for (const node of nodes) {
const currentPath = [...path, node.id];
if (node.id == targetId) {
return currentPath;
}
if (node.children && node.children.length > 0) {
const found = findNodePathById(targetId, node.children, currentPath);
if (found.length > 0) {
return found;
}
}
}
return [];
}