Element Plus的el-tree-select组件
思路: 选中节点时,给选中的节点赋值 pathLabel,pathLabel 为函数生成的节点名字拼接,数据源中不包含。
在el-tree-select组件中设置 props=“{ label: ‘pathLabel’ }” 控制选中时input框中回显的字段。选择项的名称(option-label)使用插槽#default控制。
<template>
<div class="content">
<el-tree-select filterable :data="deptData" :props="{ value: 'id', label: 'pathLabel', children: 'children' }"
@change="handleDeptData" node-key="id"
class="w100" clearable placeholder="请选择/输入分组"
check-strictly :render-after-expand="true"
v-model="deptIds">
<template #default="{ data: { name } }">
<span>{{ name }}</span>
</template>
</el-tree-select>
</div>
</template>
<script setup lang="ts">
const deptIds = ref('')
const deptData = ref([
{
id: 1100, name: '第一级', children: [
{ id: 1101, name: '1-1' ,children: [
{ id: 110101, name: '1-1-1' },
{ id: 110102, name: '1-2-2' },
{ id: 110103, name: '1-3-3' },
] },
{ id: 1102, name: '1-2' },
{ id: 1103, name: '1-3' },
]
},
{
id: 1200, name: '第二级', children: [
{ id: 1201, name: '2-1' },
{ id: 1202, name: '2-2' },
{ id: 1203, name: '2-3' },
]
},
])
const handleDeptData = (deptId: string) => {
findPath(deptData.value, deptId);
}
// 根据分组id获取分组名
function findPath(tree:any, targetId:string) {
let path = [];
let currentNode;
// 查找节点
function findNode(nodes, currentPath) {
for (let node of nodes) {
const newPath = [...currentPath, node.name];
if (node.id === targetId) {
currentNode = node;
path = newPath;
return true;
}
if (node.children && findNode(node.children, newPath)) {
return true;
}
}
return false;
}
findNode(tree, []);
// 选中节点赋值 pathLabel
if (currentNode) currentNode.pathLabel = path.length ? path.join('/') : null;
return path.length ? path.join('/') : null;
}
</script>