在后台管理系统中可能会遇到需要下拉选择树的功能,element-ui自身没有提供可以直接使用的组件,可以引用vue插件解决这个需求。但是在内网环境下开发,不方便下载依赖,简单封装一个够用的组件也是不错的选择,在网上找到相关资料学习总结后分享给大家。
<template>
<el-select
ref="select"
v-model="value"
v-bind="$attrs"
@remove-tag="removeTag"
>
<el-option value="" />
<el-tree
ref="treeOption"
:show-checkbox="this.$attrs.multiple"
default-expand-all
highlight-current
node-key="id"
check-on-click-node
:data="options"
:props="defaultProps"
@check="checkNode"
/>
</el-select>
</template>
<script>
export default {
componentName: "SelectTree",
props: {
// 节点数据
options: {
type: Array, // 必须是树形结构的对象数组
default() {
return [];
},
},
// 设置lable
defaultProps: {
type: Object,
default() {
return {
label: "name", // 显示名称
children: "children", // 子级字段名
};
},
},
// 默认勾选的节点
defaultCheckNodes: {
type: Array,
default() {
return [];
},
},
},
data() {
return {
value: [],
};
},
watch: {
defaultCheckNodes: {
handler: function (val) {
this.handleChecked(val);
},
// immediate: true // 第一次触发读取不到this解决方法有2种,watch的回调函数放在this.$nextTick()
// 不使用immediate: true,在mounted触发一次
},
},
mounted() {
this.defaultCheckNodes.forEach((item) => {
this.checkNode(item);
});
},
methods: {
// 删除tag时,
removeTag(val) {
// 取消勾选
const treeOption = this.$refs.treeOption;
treeOption.setChecked(val, false, false);
// 重新给控件赋值
this.$emit("input", this.value);
},
// 勾选节点,
checkNode(node, treeStatus) {
node.value = node.id;
node.currentLabel = node.name;
// 给selectTree的cachedOptions赋值 设置node.label,使用页面显示label值
const select = this.$refs.select;
select.cachedOptions.push(node);
select.handleOptionSelect(node, true);
this.$emit("input", this.value);
},
// 处理默认勾选
handleChecked(nodeList) {
nodeList.forEach((item) => {
this.checkNode(item);
});
},
},
};
</script>
<style lang="scss" scoped>
.el-scrollbar {
.el-scrollbar__view {
.el-select-dropdown__item {
height: auto;
padding: 0;
}
}
}
</style>