调用
单选调用(传入字符串):<select-tree :treeData='departAll' :id.sync="returnString"></select-tree>
多选调用(传入数组):<select-tree :treeData='departAll' multiple :id.sync="returnArray"></select-tree>
组件内容
<template>
<div>
<el-select ref="select" v-model="treeShowValue" :clearable="true" :multiple="multiple" :placeholder="tipText" @click.native="isShowSelect = !isShowSelect">
</el-select>
<el-popover placement="bottom" trigger="manual" v-model="isShowSelect">
<el-tree v-if="isShowSelect" :data="treeData" :node-key="nodeKey" :show-checkbox="multiple" :expand-on-click-node="multiple" :default-expanded-keys="defaultExpandedKeys" :default-checked-keys="defaultCheckedKeys" :default-expand-all="defaultExpandAll" highlight-current @node-click="handleNodeClick" @check="getKeys" :props="defaultProps">
</el-tree>
</el-popover>
</div>
</template>
<script>
import { validatenull } from '@/util/validate'
export default {
props: {
treeData: {type: Array, required: true},
defaultExpandAll: {
type: Boolean,
default: false
},
multiple: {
type: Boolean,
default: false
},
id: [String, Array],
nodeKey: {type: String, default: 'id'},
tipText: {type: String, default: '请选择'}
},
data () {
return {
// 是否显示树状选择器
isShowSelect: false,
key: [],
showValueTmp: '',
treeShowValue: this.multiple ? [] : '',
defaultExpandedKeys: [],
defaultCheckedKeys: [],
defaultProps: {
children: 'children',
label: 'label'
}
}
},
watch: {
isShowSelect (val) {
// 隐藏select自带的下拉框
this.$refs.select.blur()
if (val) {
// 下拉面板展开-选中节点-展开节点
this.setTreeCheckNode(this.key)
this.defaultCheckedKeys = this.key
this.defaultExpandedKeys = this.key
}
},
key (val) {
if (this.multiple) {
this.$emit('update:id', this.key)
} else {
this.$emit('update:id', this.key[0])
}
}
},
mounted () {
// 把传进来的参数转成数组处理
if (this.multiple && Array.isArray(this.id)) {
this.key = this.id
} else {
this.key.push(this.id)
}
this.setTreeCheckNode(this.key)
},
methods: {
handleNodeClick (data) {
if (!this.multiple) {
this.treeShowValue = data.label
this.key = [data.id]
this.isShowSelect = !this.isShowSelect
}
},
getKeys (data, checked) {
let tmp = []
for (let index = 0; index < checked.checkedNodes.length; index++) {
tmp.push(checked.checkedNodes[index].label)
}
this.treeShowValue = tmp
this.key = checked.checkedKeys
},
setTreeCheckNode (ids) {
let tmp = []
ids.forEach(id => {
this.findTreeNode(this.treeData, id)
tmp.push(this.showValueTmp)
})
if (this.multiple) {
this.treeShowValue = tmp
} else {
this.treeShowValue = tmp[0]
}
},
// 递归查询树形节点
findTreeNode (tree, id) {
if ((!validatenull(tree)) && (!validatenull(id))) {
for (var i = 0; i < tree.length; i++) {
if (tree[i].id === id) {
this.showValueTmp = tree[i].label
} else if (tree[i].children != null && tree[i].children.length > 0) {
this.findTreeNode(tree[i].children, id)
}
}
}
}
}
}
</script>