uniapp 递归实现无限层级树点击变色

该文章展示了一个名为uniTree.vue的Vue组件,用于构建树形菜单结构。组件利用递归实现子节点的展开与收缩,并通过自定义事件Bus进行父子组件间的数据通信,例如选中节点的id。组件样式包括节点的字体颜色、背景色和图标状态,以控制树的展开状态。
摘要由CSDN通过智能技术生成

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(); 

效果图
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值