通过el-select选择器和el-tree树形结构二次封装(vue2+elementUI),开发element-plus的TreeSelect树形选择器
在Vue 2和Element UI的环境下,可以通过自定义指令来封装一个可以使用el-select
选择器和el-tree
树形结构的组件。以下是一个简单的示例:
- 创建一个Vue组件
TreeSelect.vue
:
<template>
<el-popover
ref="popover"
placement="bottom-start"
width="200"
trigger="click"
@show="$refs.tree.filter(filterText)"
>
<el-tree
:data="data"
:props="defaultProps"
:filter-node-method="filterNode"
ref="tree"
@node-click="handleNodeClick"
/>
<el-select
slot="reference"
:value="selectedLabel"
@change="handleChange"
style="width: 100%;"
ref="select"
>
<el-option :value="selectedLabel" style="height: auto">
<div :style="{ padding: '5px', width: '100%' }" @click.stop="">
{{ selectedLabel }}
<i slot="suffix" class="el-input__icon el-icon-arrow-down" />
</div>
</el-option>
</el-select>
</el-popover>
</template>
<script>
export default {
props: {
data: {
type: Array,
default: () => [],
},
props: {
type: Object,
default: () => ({
label: 'label',
children: 'children',
}),
},
value: [String, Number],
filterable: Boolean,
},
data() {
return {
selected: null,
filterText: '',
defaultProps: this.props,
};
},
computed: {
selectedLabel() {
const node = this.data.find((d) => d[this.defaultProps.label] === this.selected);
return node ? node[this.defaultProps.label] : '';
},
},
watch: {
value(val) {
this.selected = val;
},
},
methods: {
handleChange(value) {
this.$emit('input', value);
this.$refs.popover.doClose();
},
handleNodeClick(data) {
this.selected = data[this.defaultProps.label];
this.handleChange(this.selected);
},
filterNode(value, data) {
if (!this.filterable) return true;
return data[this.defaultProps.label].indexOf(value) !== -1;
},
},
};
</script>
- 在父组件中使用该组件:
<template>
<div>
<tree-select
:data="treeData"
v-model="selectedValue"
:props="defaultProps"
filterable
/>
</div>
</template>
<script>
import TreeSelect from './TreeSelect';
export default {
components: {
TreeSelect,
},
data() {
return {
selectedValue:
评论已关闭