一、前言
有时候就会遇到组件配合使用的情况,然后就整理了一下,后面大家需要的话可以直接拿去使用。
二、源码
<template>
<el-select
ref="selectTree"
filterable
v-model="name"
:placeholder="'请选择'"
:filter-method="focus"
clearable
@focus="focus('')"
@clear="clearValue"
>
<el-option style="height: auto">
<el-tree
ref="tree"
:data="data"
:expand-on-click-node="false"
default-expand-all
node-key="categoryId"
:empty-text="'无匹配数据'"
:props="defaultProps"
highlight-current
@node-click="handleNodeClick"
:filter-node-method="filterNode"
/>
</el-option>
</el-select>
</template>
<script>
export default {
data() {
return {
name: '',
categoryId: null,
data: [
{
id: 1,
pid: null,
parentId: 0,
children: [
{
id: 2,
pid: null,
parentId: 1,
children: [
{
id: 8,
pid: null,
parentId: 2,
children: [],
postCode: '',
postName: '添加1',
sort: null,
tenantId: 120,
status: 1,
createTime: '2023-10-30 14:28:16',
childPost: null,
postType: 2,
nodeType: null,
postAdmin: 10024
},
{
id: 9,
pid: null,
parentId: 2,
children: [],
postCode: '',
postName: '测试添加',
sort: null,
tenantId: 120,
status: 1,
createTime: '2023-11-01 15:30:22',
childPost: null,
postType: 2,
nodeType: null,
postAdmin: 10022
},
{
id: 11,
pid: null,
parentId: 2,
children: [],
postCode: '',
postName: '测试',
sort: null,
tenantId: 120,
status: 1,
createTime: '2023-11-02 13:26:24',
childPost: null,
postType: 2,
nodeType: null,
postAdmin: 10024
},
{
id: 13,
pid: null,
parentId: 2,
children: [],
postCode: '',
postName: '测试111',
sort: null,
tenantId: 120,
status: 1,
createTime: '2023-11-02 13:48:44',
childPost: null,
postType: 2,
nodeType: null,
postAdmin: 10022
}
],
postCode: null,
postName: '人事部门',
sort: null,
tenantId: 120,
status: 1,
createTime: '2023-10-26 10:55:18',
childPost: null,
postType: 2,
nodeType: null,
postAdmin: null
}
],
postCode: null,
postName: '回集团根节点',
sort: null,
tenantId: 120,
status: 1,
createTime: '2023-10-26 10:55:18',
childPost: null,
postType: 1,
nodeType: 6,
postAdmin: 10000
}
],
defaultProps: {
children: 'children',
label: 'postName'
}
}
},
methods: {
filterNode(value, data) {
if (!value) return true
return data.postName.indexOf(value) !== -1
},
// 节点点击事件
handleNodeClick(data, node, nodeData) {
this.name = data.postName
this.categoryId = data.id
this.$refs.selectTree.blur()
},
// 数据集回显
echoDataSet(val) {
if (!val) return
const categoryId = val.id || ''
this.categoryId = categoryId
this.$refs.tree.setCurrentKey(categoryId) // 设置节点高亮
},
focus(val) {
this.$refs.tree.filter(val)
},
clearValue() {
this.$refs.tree.setCurrentKey(null)
}
}
}
</script>
<style>
.el-select-dropdown__item {
padding: 0;
}
</style>
关于回显只需要在编辑的时候进行name字段的赋值,以及触发代码中数据回显的方法,传入需要选中的id就可以了。