这个是我目前实现的方法,有没有更优雅点的?
handleChange(value) {
this.formInfo.checkItem = value;
// 获取选中项的 value
const selectedValue = value[value.length - 1];
// 根据 selectedValue 遍历 options 找到对应的 label
let selectedLabel = "";
this.traverseOptions(
this.options,
selectedValue,
(label, parentValue) => {
selectedLabel = label;
}
);
this.formInfo.checkClass = selectedValue; // 将找到的 selectedValue 赋值给 checkClass
this.formInfo.checkClassName = selectedLabel; // 将找到的 selectedLabel 赋值给 checkClass
},
traverseOptions(options, value, callback, parentValue) {
for (let i = 0; i < options.length; i++) {
const option = options[i];
if (option.value === value) {
let label = option.label;
callback(label, parentValue); // 找到匹配的 label 并回调传递
return;
}
if (option.children) {
this.traverseOptions(option.children, value, callback, option.value); // 递归遍历子选项,并传递父级的值
}
}
},
值绑定对象 获取的就是对象有label和value字段
