当前位置: 首页 > news >正文

el-select+el-tree实现树形下拉选择

前言

项目需求所需,记录下el-select+el-tree实现树形下拉选择

一、使用步骤

1.封装

<template><div style="display: flex"><el-selectv-model="insideValue":multiple="multiple":disabled="disabled":placeholder="placeholder":collapse-tags="collapseTags"@visible-change="handleVisibleChange"v-on="$listeners"style="width: 100%"ref="treeSelect"><!-- 添加实际的 el-option 用于显示标签 --><el-optionv-for="item in selectedOptions":key="item.value":label="item.label":value="item.value"style="display: none"/><!-- 树形选择器 --><el-option style="height: auto; padding: 0" :value="insideValue"><el-treev-show="showTree":data="options":show-checkbox="multiple":props="defaultProps"v-on="$listeners":highlight-current="true"node-key="orgCode"ref="tree":check-strictly="checkStrictly"@node-click="handleNodeClick"@check="handleCheckChange":default-expanded-keys="defaultExpandedKeys"></el-tree></el-option></el-select></div>
</template><script lang="ts">
import { Vue, Component, Prop, Watch, Ref } from 'vue-property-decorator'interface TreeNode {orgCode: stringorgName: stringchildren?: TreeNode[]
}interface SelectOption {value: stringlabel: string
}@Component({name: 'comTreeSelect'
})
export default class ComTreeSelect extends Vue {@Prop({ type: [String, Array] }) value!: string | string[]@Prop({ type: Boolean, default: false }) disabled!: boolean@Prop({ type: Boolean, default: false }) multiple!: boolean@Prop({ type: String, default: '请选择' }) placeholder!: string@Prop({ type: Boolean, default: false }) collapseTags!: boolean@Prop({ type: Boolean, default: true }) selectShow!: boolean@Prop({ type: Boolean, default: true }) checkStrictly!: boolean@Ref('treeSelect') treeSelectRef!: any@Ref('tree') treeRef!: anycomponentInit = falseinsideValue: string | string[] = this.multiple ? [] : ''options: TreeNode[] = []selectedOptions: SelectOption[] = [] // 用于存储选中的选项loading = falseshowTree = falsedefaultProps = {children: 'children',label: 'orgName',value: 'orgCode'}searchMap = {pageIndex: 1,pageSize: 999,search: {}}get selectedLabelText(): string {return this.selectedOptions.map((option) => option.label).join(', ')}get defaultExpandedKeys(): any {const keys = []this.options.forEach((node) => {keys.push(node.orgCode)})return keys}@Watch('value', { immediate: true })onValueChange(newVal: string | string[]): void {this.insideValue = this.multiple ? newVal || [] : newVal || ''// 如果组件已经初始化,需要同步树的选择状态if (this.componentInit) {this.syncTreeSelection()}}@Watch('insideValue')onInsideValueChange(newVal: string | string[]): void {this.$emit('input', newVal)}async getRemoteList(): Promise<void> {try {this.loading = trueconst { code, result } = await this.$agencyManage.list(this.searchMap, { isLoading: false })if (code === 200) {this.options = result ? result.items || [] : []// 数据加载完成后同步选择状态this.syncTreeSelection()}} catch (error) {console.error('获取机构列表失败:', error)} finally {this.loading = false}}// 同步树的选择状态syncTreeSelection(): void {this.$nextTick(() => {if (this.multiple && Array.isArray(this.insideValue)) {this.treeRef?.setCheckedKeys(this.insideValue)this.updateSelectedOptions()this.$emit('change', this.insideValue)} else if (!this.multiple && typeof this.insideValue === 'string') {this.treeRef?.setCurrentKey(this.insideValue)this.updateSelectedOptions()this.$emit('change', this.insideValue)}})}// 更新选中的选项updateSelectedOptions(): void {if (this.multiple) {const checkedNodes = this.treeRef?.getCheckedNodes() || []this.selectedOptions = checkedNodes.map((node: TreeNode) => ({value: node.orgCode,label: node.orgName}))} else {const currentNode = this.treeRef?.getCurrentNode()console.log('currentNode', currentNode)this.selectedOptions = currentNode ? [{ value: currentNode.orgCode, label: currentNode.orgName }] : []}}handleVisibleChange(visible: boolean): void {this.showTree = visibleif (visible) {this.$nextTick(() => {this.syncTreeSelection()})}}handleNodeClick(node: TreeNode): void {if (!this.multiple) {this.insideValue = node.orgCodethis.selectedOptions = [{value: node.orgCode,label: node.orgName}]this.$emit('input', this.insideValue)this.$emit('change', this.insideValue)this.showTree = falsethis.treeSelectRef.blur()}}handleCheckChange(): void {if (this.multiple) {const checkedNodes = this.treeRef?.getCheckedNodes() || []this.insideValue = checkedNodes.map((node: TreeNode) => node.orgCode)this.selectedOptions = checkedNodes.map((node: TreeNode) => ({value: node.orgCode,label: node.orgName}))this.$emit('input', this.insideValue)this.$emit('change', this.insideValue)}}mounted(): void {this.$nextTick(() => {if (!this.componentInit) {this.getRemoteList()}})}activated(): void {this.componentInit = truethis.getRemoteList()}handleChange(): void {this.insideValue = this.multiple ? [] : ''}
}
</script><style scoped lang="scss">
.el-select {.el-input--mini .el-input__inner {height: 28px !important;line-height: 28px !important;}/* 修复树形选择器的样式 */.el-tree {padding: 5px;min-width: 100%;box-sizing: border-box;}
}
</style>

2.使用 

 <com-tree-selectv-model="value":disabled="false":multiple="true":collapseTags="true":checkStrictly="true/>

总结

以上是我封装的组件,如有问题,可以提出。

http://www.xdnf.cn/news/998479.html

相关文章:

  • tabs页签嵌套表格,切换表格保存数据不变并回勾
  • CSS 外边距合并(Margin Collapsing)问题研究
  • Karate 与Playwright的比较和融合
  • spring boot项目整合mybatis实现多数据源的配置
  • RAG Food Project
  • GAN+ECA注意力机制实现图像超分辨率重建
  • ESP32-C3FH4X—低功耗、高集成度的 MCU 系统级芯片 (SoC)
  • 基于数据库实现配置管理和定时任务启停
  • 强化学习:策略梯度概念
  • word用endnote插入国标参考文献
  • 在 Flutter 项目中iOS 的 App 图标和 App 名称 的设置
  • 探索 Excel-to-JSON:高效数据转换的利器
  • Linux Alias 魔法:命令行效率提升秘籍
  • R语言缓释制剂QBD解决方案之四
  • RK3588 + Ubuntu24.04 部署 rknn 模型——不用[特殊字符]版全流程教程
  • 管家婆软件下载中心-管家婆软件辉煌安装包下载、应用程序、最新版软件
  • STL难记忆却常用的用法集合(持续更新中)
  • 自动驾驶系统研发系列—AI大模型驱动的智能座舱:从概念到落地的工程解析
  • MonkeyOCR: 基于结构-识别-关系三元组范式的文档解析
  • 客户端登录not foud的问题解决
  • PostgreSQL 用户名大小写处理规则
  • 黑龙江亿林网络启盛裸金属服务器评测:24 核 32G + 联通千兆共享,高负载业务的新利器
  • ​​​​​​​《TCP/IP协议卷1》第9章 IP选路
  • 鸟类识别与分类相关数据集(猫脸码客第252期)
  • 医疗行业网络安全的综合防护策略
  • 大模型在关键社会领域的应用研究:金融、医疗和法律
  • 一种安全实用、准确率高的Text2Sql方案
  • element 跨页选中,回显el-table选中数据
  • 《linux2.4内存管理》第3章 页表管理
  • 《TCP/IP协议卷1》 TCP的坚持和保活定时器