<template>
|
<div>
|
<div class="tree-box">
|
<el-tree
|
ref="tree"
|
:data="treeList"
|
node-key="id"
|
:props="{
|
'label':'name'
|
}"
|
@node-expand="onExpand"
|
@node-click="onSelect"
|
:expand-on-click-node="false"
|
:default-expand-all="autoExpandParent"
|
highlight-current="true"
|
>
|
</el-tree>
|
</div>
|
</div>
|
</template>
|
|
<script>
|
|
export default {
|
props: {// 第二种方式
|
treeList: {
|
type: Array,
|
default: function () {
|
return []
|
}
|
}
|
},
|
data () {
|
return {
|
expandedKeys: [],
|
searchValue: '',
|
autoExpandParent: false,
|
dataList: []
|
}
|
},
|
watch: {
|
treeList (curVal) {
|
if (curVal) {
|
this.generateList(curVal)
|
this.treeList = curVal
|
}
|
}
|
},
|
methods: {
|
onExpand (expandedKeys) {
|
this.expandedKeys = expandedKeys
|
this.autoExpandParent = false
|
},
|
onChange (e) {
|
const value = e
|
const expandedKeys = this.dataList.map(item => {
|
if (item.label.indexOf(value) > -1) {
|
return this.getParentKey(item.id, this.treeList)
|
}
|
return null
|
})
|
.filter((item, i, self) => item && self.indexOf(item) === i)
|
Object.assign(this, {
|
expandedKeys,
|
searchValue: value,
|
autoExpandParent: true
|
})
|
},
|
getParentKey (id, tree) {
|
let parentKey
|
for (let i = 0; i < tree.length; i++) {
|
const node = tree[i]
|
if (node.children) {
|
if (node.children.some(item => item.id === id)) {
|
parentKey = node.id
|
} else if (this.getParentKey(id, node.children)) {
|
parentKey = this.getParentKey(id, node.children)
|
}
|
}
|
}
|
return parentKey
|
},
|
generateList (data) {
|
//id 和 对象能获取到
|
for (let i = 0; i < data.length; i++) {
|
const node = data[i]
|
const id = node.id
|
console.log(id+'id')
|
console.log(node.name+'name')
|
this.dataList.push({ id: id, label: node.name })
|
}
|
},
|
onSelect (selectedNodes) {
|
console.log(selectedNodes.id)
|
console.log(selectedNodes.name)
|
const param = { id: selectedNodes.id, name: selectedNodes.name }
|
this.$emit('setNode', param)
|
},
|
refshData(){
|
this.$refs.tree.setCheckedKeys([]);
|
this.$emit('setNode', {})
|
}
|
}
|
}
|
</script>
|
<style scoped>
|
/deep/ .el-tree-node__content{
|
font-size: 14px;
|
height: 40px;
|
line-height: 40px;
|
}
|
.font-14{
|
font-size: 14px;
|
}
|
.tree-box{
|
position: relative;
|
max-height: calc(100vh - 306px);
|
overflow-y: scroll;
|
}
|
.tree-box::-webkit-scrollbar{
|
width: 5px;
|
}
|
.refresh-btn{
|
cursor: pointer;
|
position: absolute;
|
top:0;
|
right:0;
|
font-size: 14px;
|
z-index: 101;
|
line-height: 40px;
|
color: #999;
|
text-align: right;
|
}
|
.refresh-btn:hover{
|
color: #0c8aff;
|
}
|
</style>
|