前言:项目中引用的前端组件库是elementui,需求是实现一个下拉列表框含树形结构。来记录一下啦
<el-select
v-model="content"
placeholder="请选择"
clearable
@clear="handleClear"
ref="selectUpResId"
>
<el-option
:value="parlancePassage.parentId"
key="id"
:label="label"
style="height: auto"
>
<el-tree
:data="dataList"
:props="defaultProps"
ref="tree"
node-key="id"
:expand-on-click-node="false"
@node-click="handleNodeClick"
></el-tree>
</el-option>
</el-select>
注意绑定的数据要是树形对象数组,如你的值是扁平数据需要对数据进行转换
handleNodeClick(data, node, el) {
this.label = data.label;
this.parlancePassage.parentId = data.id;
this.content = data.label;
选择完成后失去焦点
this.$refs.selectUpResId.blur();
},
点击清空按钮触发事件
handleClear() {
// 将选择器的值置空
this.label = "";
this.parlancePassage.parentId = "";
},
树形数据的的转换方法(使用递归)
transformData(data) {
const result = [];
result.push({
id: 0,
label: "根节点",
});
const traverse = (item) => {
const newItem = {
id: item.id,
label: item.passageName,
children: [],
};
if (item.children && item.children.length > 0) {
item.children.forEach((child) => {
const newChild = traverse(child);
newItem.children.push(newChild);
});
}
return newItem;
};
data.forEach((item) => {
const newItem = traverse(item);
result.push(newItem);
});
return result;
},