uniTree.vue
<template>
<view>
<view :index="item.id" class="treeMenu" >
<view class="tree-it" :class="['font-'+item.level+'-'+ (item.children != null), item.id == checkedUnitId? 'tree-it-checked':'']" :style="{paddingLeft: item.level*20 + 'px'}" @tap.stop.prevent="childrenClick(item)">
{{ item.label }}
<image v-if="item.children != null" class="right-icon" :src="item.open?openIcon:closeIcon" @tap.stop.prevent @tap="changeTreeStatus(item)"/>
</view>
<view class="line-cent"></view>
<view v-if="item.children != null && item.open">
<unit-tree v-for="it in item.children" :item="it"></unit-tree> <!--引用自身,实现递归-->
</view>
</view>
</view>
</template>
<script>
import { selectUnitTree } from '@/api/unit/unit';
import unitTree from "./unitTree"; //引入自己,实现递归
import Bus from '@/utils/bus.js';//用这种方法实际上是用一个中介来传递数据,可以实现递归组件和使用它的组件之间的解耦。
export default {
components: {
unitTree
},
name: 'unitTree',
props: {
item: {
type: Object,
default: null
}
},
data() {
return {
unitTreeList: [],
openIcon: "/static/images/tree/icon-arrow-open.png",
closeIcon: "/static/images/tree/icon-arrow-close.png",
checkedUnitId: ''
}
},
created() {
Bus.$on('getTarget', target => {
this.checkedUnitId = target;
});
},
methods: {
getUnitTree(){
selectUnitTree().then(res => {
this.unitTreeList = res.data;
})
},
changeTreeStatus(item){
item.open = !item.open;
},
childrenClick(unit){
Bus.$emit('getTarget', unit.id);
},
}
}
</script>
<style>
.treeMenu{
font-size: 20px;
letter-spacing: 3px;
line-height: 40px;
background-color: #F2F7FD;
}
.line-cent{
width: 100%;
height: 2px;
background-color: #fff;
}
.tree-it{
display: flex;
}
/* .tree-it:hover{
background-color: #E6EDFA;
} */
.tree-it-checked{
background-color: #E6EDFA;
}
.font-2-true{
color: #114ED9;
}
.font-3-true, .font-4-true, .font-5-true{
color: #333333;
}
.font-3-false, .font-4-false, .font-5-false{
color: #999999;
}
.right-icon{
float: right;
width: 19px;
height: 8px;
margin: auto;
margin-right: 10px;
}
</style>
bus.js
import Vue from 'vue';
export default new Vue();
效果图