输入框下拉树组件,并设置只显示最后一级节点
完整代码如下
<template>
<el-form :model="formData" style="max-width: 600px; margin: 0 auto;">
<el-form-item label="树形选择输入框" prop="question_category">
<el-popover placement="bottom" width="350" trigger="click">
<el-tree
ref="treeRef"
:data="tree"
:check-strictly="false"
show-checkbox
default-expand-all
node-key="id"
:default-expanded-keys="[]"
:default-checked-keys="[]"
:props="{
children: 'children',
label: 'name'
}"
@check-change="handleTreeCheckChange"
>
</el-tree>
<template v-slot:reference>
<el-input
placeholder="树形选择输入框"
:model-value="formData.category.map((cat) => cat.name).join(', ')"
>
</el-input>
</template>
</el-popover>
</el-form-item>
</el-form>
</template>
<script lang="ts" setup>
import type { ElTree } from 'element-plus'
import { onMounted } from 'vue'
// 行业岗位分类
const treeRef = ref<InstanceType<typeof ElTree>>()
const tree = ref<
{
id: string
name: string
children: { id: string; name: string; children?: any[] | undefined }[]
}[]
>([])
// 表单数据
const formData = reactive<{
category: { id: string; name: string }[]
}>({
category: []
})
// 获取分类数据
const fetchCategories = async () => {
tree.value = [
{
id: '1',
name: 'Root',
children: [
{
id: '2',
name: 'Child 1',
children: [
{
id: '3',
name: 'Child 1.1',
children: []
},
{
id: '4',
name: 'Child 1.2',
children: []
}
]
},
{
id: '5',
name: 'Child 2',
children: [
{
id: '6',
name: 'Child 2.1',
children: []
}
]
},
{
id: '7',
name: 'Child 3',
children: []
}
]
}
]
}
// 更新分类数据
const handleTreeCheckChange = () => {
// 递归地遍历树结构来获取所有的最终子节点
const getFinalChildren = (nodes: any[]): any[] => {
return nodes.flatMap((node) => {
if (node.children && node.children.length > 0) {
return getFinalChildren(node.children)
} else {
return [node]
}
})
}
formData.category = getFinalChildren(tree.value)
.filter((child) => treeRef.value!.getCheckedKeys().includes(child.id))
.map(({ id, name }) => ({ id, name }))
}
onMounted(() => {
fetchCategories()
})
</script>