人家antd都支持,elementplus 也支持,vue2的沒有,很煩。
網上其實可以搜到各種的,不過大部分不支持重名,在刪除的時候可能會刪錯,比如樹結構1F的1樓啊,2F的1樓啊這種同時勾選的情況。。
可以全路徑
干凈點不要全路徑也可以,
一股腦全放,可能有一點無效代碼,懶得刪了,等出bug再說
<template><!-- <t-tree-select:options="treeList"placeholder="請選擇tree結構"width="50%":defaultData="defaultValue":treeProps="treeProps"@handleNodeClick="selectDrop"
/> --><el-selectref="select"v-model="displayValues":multiple="multiple":filter-method="dataFilter"@remove-tag="removeTag"@clear="clearAll"popper-class="t-tree-select":style="{width: width||'100%'}"v-bind="attrs"v-on="$listeners" popper-append-to-bodyclass="select-tree"><el-option v-model="selectTree" class="option-style" disabled ><div class="check-box" v-if="multiple&&checkBoxBtn"><el-button type="text" @click="handlecheckAll">{{checkAllText}}</el-button><el-button type="text" @click="handleReset">{{resetText}}</el-button><el-button type="text" @click="handleReverseCheck">{{reverseCheckText}}</el-button></div> <el-tree:data="options":props="treeProps"class="tree-style"ref="treeNode":check-strictly="true":show-checkbox="multiple":node-key="treeProps.value":filter-node-method="filterNode":default-checked-keys="defaultValue":current-node-key="currentKey"@node-click="handleTreeClick"@check-change="handleNodeChange"v-bind="treeAttrs"v-on="$listeners"></el-tree></el-option></el-select>
</template><script>
export default {name: 'TTreeSelect',props: {// 多選默認值數組defaultValue: {type: Array,default: () => []},// 單選默認展示數據必須是{id:***,label:***}格式defaultData: {type: Object},// 全選文字checkAllText: {type: String,default: '全選'},// 清空文字resetText: {type: String,default: '清空'},// 反選文字reverseCheckText: {type: String,default: '反選'},// 可用選項的數組options: {type: Array,default: () => []},// 配置選項——>屬性值為后端返回的對應的字段名treeProps: {type: Object,default: () => ({value: 'value', // ID字段名label: 'title', // 顯示名稱children: 'children' // 子級字段名})},// 是否顯示全選、反選、清空操作checkBoxBtn: {type: Boolean,default: false},// 是否多選multiple: {type: Boolean,default: true},// 選擇框寬度width: {type: String},// 是否顯示完整路徑, 如 1樓-1f-101showFullPath: {type: Boolean,default: true}},data() {return {selectTree: this.multiple ? [] : '', // 綁定el-option的值currentKey: null, // 當前選中的節點filterText: null, // 篩選值VALUE_NAME: this.treeProps.value, // value轉換后的字段VALUE_TEXT: this.treeProps.label, // label轉換后的字段selectedNodes: [] // 存儲選中的完整節點信息}},computed: {attrs() {return {'popper-append-to-body': false,clearable: true,filterable: true,...this.$attrs}},// tree屬性treeAttrs() {return {'default-expand-all': true,...this.$attrs}},// 顯示值:根據showFullPath決定顯示內容displayValues() {if (this.multiple) {return this.selectedNodes.map(node => this.showFullPath ? this.getNodePath(node) : node[this.VALUE_TEXT])}const firstNode = this.selectedNodes[0]if (!firstNode) return ''return this.showFullPath ? this.getNodePath(firstNode) : firstNode[this.VALUE_TEXT]}},watch: {defaultValue: {handler() {this.$nextTick(() => {// 多選if (this.multiple) {let datalist = this.$refs.treeNode.getCheckedNodes()this.selectTree = datalistthis.selectedNodes = [...datalist]}})},deep: true},// 對樹節點進行篩選操作filterText(val) {this.$refs.treeNode.filter(val)}},mounted() {this.$nextTick(() => {const scrollWrap = document.querySelectorAll(".el-scrollbar .el-select-dropdown__wrap")[0];const scrollBar = document.querySelectorAll(".el-scrollbar .el-scrollbar__bar");scrollWrap.style.cssText ="margin: 0px; max-height: none; overflow: hidden;";scrollBar.forEach((ele) => {ele.style.width = 0;});});if (this.multiple) {let datalist = this.$refs.treeNode.getCheckedNodes()this.selectTree = datalistthis.selectedNodes = [...datalist]}// 有defaultData值才回顯默認值if (this.defaultData?.id) {this.setDefaultValue(this.defaultData)}},methods: {// 獲取節點的完整路徑getNodePath(node) {const path = []let currentNode = node// 向上查找父節點,構建路徑while (currentNode) {path.unshift(currentNode[this.VALUE_TEXT])currentNode = this.findParentNode(currentNode, this.options)}return path.join('-')},// 查找父節點findParentNode(targetNode, nodes, parent = null) {for (let node of nodes) {if (node[this.VALUE_NAME] === targetNode[this.VALUE_NAME]) {return parent}if (node.children && node.children.length > 0) {const found = this.findParentNode(targetNode, node.children, node)if (found !== null) {return found}}}return null},// 單選設置默認值setDefaultValue(obj) {if (obj.label !== '' && obj.id !== '') {this.selectTree = obj.idthis.selectedNodes = [{ [this.VALUE_NAME]: obj.id, [this.VALUE_TEXT]: obj.label }]this.$nextTick(() => {this.currentKey = this.selectTreethis.setTreeChecked(this.selectTree)})}},// 全選handlecheckAll() {setTimeout(() => {this.$refs.treeNode.setCheckedNodes(this.options)}, 200)},// 清空handleReset() {setTimeout(() => {this.$refs.treeNode.setCheckedNodes([])}, 200)},/*** @description: 反選處理方法* @param {*} nodes 整個tree的數據* @param {*} refs this.$refs.treeNode* @param {*} flag 選中狀態* @param {*} seleteds 當前選中的節點* @return {*}*/batchSelect(nodes, refs, flag, seleteds) {if (Array.isArray(nodes)) {nodes.forEach(element => {refs.setChecked(element, flag, true)})}if (Array.isArray(seleteds)) {seleteds.forEach(node => {refs.setChecked(node, !flag, true)})}},// 反選handleReverseCheck() {setTimeout(() => {let res = this.$refs.treeNodelet nodes = res.getCheckedNodes(true, true)this.batchSelect(this.options, res, true, nodes)}, 200)},// 輸入框關鍵字dataFilter(val) {setTimeout(() => {this.filterText = val}, 100)},/*** @description: tree搜索過濾* @param {*} value 搜索的關鍵字* @param {*} data 篩選到的節點* @return {*}*/filterNode(value, data) {if (!value) return truereturn data[this.treeProps.label].toLowerCase().indexOf(value.toLowerCase()) !== -1},/*** @description: 勾選樹形選項* @param {*} data 該節點所對應的對象* @param {*} self 節點本身是否被選中* @param {*} child 節點的子樹中是否有被選中的節點* @return {*}*/// 多選賦值組件handleNodeChange(data, self, child) {let datalist = this.$refs.treeNode.getCheckedNodes()this.$nextTick(() => {this.selectTree = datalistthis.selectedNodes = [...datalist]this.$emit('handleNodeClick', this.selectTree)})},// 單選tree點擊賦值handleTreeClick(data, node) {if (this.multiple) {} else {this.filterText = ''this.selectTree = data[this.VALUE_NAME]this.selectedNodes = [data]this.currentKey = this.selectTreethis.highlightNode = data[this.VALUE_NAME]this.$emit('handleNodeClick', { id: this.selectTree, label: data[this.VALUE_TEXT] }, node)this.setTreeChecked(this.highlightNode)this.$refs.select.blur()}},setTreeChecked(highlightNode) {if (this.treeAttrs.hasOwnProperty('show-checkbox')) {// 通過 keys 設置目前勾選的節點,使用此方法必須設置 node-key 屬性this.$refs.treeNode.setCheckedKeys([highlightNode])} else {// 通過 key 設置某個節點的當前選中狀態,使用此方法必須設置 node-key 屬性this.$refs.treeNode.setCurrentKey(highlightNode)}},// 移除單個標簽removeTag(displayText) {let nodeIndex = -1if (this.showFullPath) {// 完整路徑模式:根據完整路徑精確匹配nodeIndex = this.selectedNodes.findIndex(node => this.getNodePath(node) === displayText)} else {// 普通模式:根據文本匹配,刪除最后一個匹配項nodeIndex = this.selectedNodes.map(node => node[this.VALUE_TEXT]).lastIndexOf(displayText)}if (nodeIndex !== -1) {const nodeToRemove = this.selectedNodes[nodeIndex]// 從selectedNodes中移除this.selectedNodes.splice(nodeIndex, 1)// 從selectTree中移除對應的節點const treeNodeIndex = this.selectTree.findIndex(v => v[this.VALUE_NAME] === nodeToRemove[this.VALUE_NAME])if (treeNodeIndex !== -1) {this.selectTree.splice(treeNodeIndex, 1)}// 更新樹的選中狀態this.$nextTick(() => {this.$refs.treeNode.setCheckedNodes(this.selectTree)})this.$emit('handleNodeClick', this.selectTree)}},// 文本框清空clearAll() {this.selectTree = this.multiple ? [] : ''this.selectedNodes = []this.$refs.treeNode.setCheckedNodes([])this.$emit('handleNodeClick', this.selectTree)}}}
</script><style scoped lang="scss">
.t-tree-select {.check-box {padding: 0 20px;}.option-style {height: 100%;max-height: 300px;margin: 0;overflow-y: auto;cursor: default !important;}.tree-style {::v-deep .el-tree-node.is-current > .el-tree-node__content {color: #3370ff;}}.el-select-dropdown__item.selected {font-weight: 500;}.el-input__inner {height: 36px;line-height: 36px;}.el-input__icon {line-height: 36px;}.el-tree-node__content {height: 32px;}}
</style>
<style lang="scss" scoped>
::v-deep .el-tree{background: #262F40 !important;color: #FFFFFF;
}
.el-scrollbar .el-scrollbar__view .el-select-dropdown__item {height: auto;max-height: 300px;padding: 0;overflow: hidden;overflow-y: auto;
}.el-select-dropdown__item.selected {font-weight: normal;
}ul li >>> .el-tree .el-tree-node__content {height: auto;padding: 0 20px;
}.el-tree-node__label {font-weight: normal;
}.el-tree >>> .is-current .el-tree-node__label {// color: #409eff;font-weight: 700;
}.el-tree >>> .is-current .el-tree-node__children .el-tree-node__label {// color: #606266;font-weight: normal;
}::v-deep .el-tree-node__content:hover,
::v-deep .el-tree-node__content:active,
::v-deep .is-current > div:first-child,
::v-deep .el-tree-node__content:focus {background-color: rgba(#333F52, 0.5);color: #409eff;
}
::v-deep .el-tree-node__content:hover {background-color: rgba(#333F52, 0.5);color: #409eff;
}::v-deep .el-tree-node:focus>.el-tree-node__content{background-color: rgba(#333F52, 0.5);}
.el-popper {z-index: 9999;
}.el-select-dropdown__item::-webkit-scrollbar {display: none !important;
}.el-select {::v-deep.el-tag__close {// display: none !important; //隱藏在下拉框多選時單個刪除的按鈕}
}
</style><style lang="scss" >
.select-tree {.el-tag.el-tag--info{color: #fff;border-color:none;background: #273142 !important;}.el-icon-close:before{color: rgba(245, 63, 63, 1); }.el-tag__close.el-icon-close{background-color: transparent !important;}
}
</style>