vue2封装el-select,el-tree,支持筛选,实现TreeSelect的效果
在Vue 2中,你可以通过封装一个组件来实现类似TreeSelect
的效果,使用el-select
和el-tree
来实现。以下是一个简单的示例:
<template>
<el-popover
ref="popover"
placement="bottom-start"
trigger="click"
@show="$refs.tree.filter('')"
>
<el-tree
:data="data"
:props="defaultProps"
ref="tree"
:filter-node-method="filterNode"
@node-click="handleNodeClick"
/>
<el-select
slot="reference"
v-model="selectedLabel"
:clearable="true"
@clear="clearSelection"
>
<template slot="prefix">
<i class="el-input__icon el-icon-arrow-down" />
</template>
</el-select>
</el-popover>
</template>
<script>
export default {
props: {
data: {
type: Array,
default: () => []
},
props: {
type: Object,
default: () => ({
label: 'label',
children: 'children'
})
},
value: [String, Number]
},
data() {
return {
selectedLabel: '',
selectedValue: this.value,
defaultProps: this.props
};
},
watch: {
value(newVal) {
this.selectedValue = newVal;
this.selectedLabel = this.getNodeLabel(this.data, newVal);
}
},
methods: {
filterNode(value, data) {
if (!value) return true;
return data[this.defaultProps.label].indexOf(value) !== -1;
},
handleNodeClick(data) {
this.selectedValue = data[this.defaultProps.value];
this.selectedLabel = data[this.defaultProps.label];
this.$refs.popover.doClose();
this.$emit('input', this.selectedValue);
},
clearSelection() {
this.selectedLabel = '';
this.selectedValue = null;
this.$emit('input', null);
},
getNodeLabel(nodes, value) {
for (let i = 0; i < nodes.length; i++) {
if (nodes[i][this.defaultProps.value] === value) {
return nodes[i][this.defaultProps.label];
}
if (nodes[i][this.defaultProps.children]) {
const label = this.getNodeLabel(nodes[i][this.defaultProps.children], value);
if (label) return label;
}
}
return '';
}
}
};
</script>
使用此组件时,你需要传递data
(树形数据),props
(指定节点标签和值的属性名),以及一个v-model
来实现数据的双向绑定。
<template>
<tree-select v-model=
评论已关闭