uniapp applet: commonly used tab bar switching, changing the corresponding content

1. The effect to be achieved is as follows:

insert image description here

2. Code implementation:

2.1 html

<template>
	<view>
		<!-- tab栏切换动态改变激活样式 -->
		<view class="nav">
			<view class="nav-list" v-for="(item,index) in list" :key="item.id" @tap="changeAct(item)">

				<!-- 激活样式名字是红色 判断act==index 和act==item.id都行-->
				<view :class="[act==index?'name':'']">
					{
   
   {item.name}}
				</view>
				<!-- 名字下面的横线 -->
				<view :class="[act==index?'line':'']">
				</view>
			</view>

		</view>

		<!-- 内容的改变 -->
		<view class="content">
			<view class="">
				{
   
   {content.id}}
			</view>
			<view class="">
				{
   
   {content.name}}
			</view>
		</view>
	</view>
</template>

2.2 js

<script>
	export default {
    
    
		data() {
    
    
			return {
    
    
				// 默认激活样式是第一个
				act: 0,

				list: [{
    
    
						id: 0,
						name: '吃饭'
					},
					{
    
    
						id: 1,
						name: '睡觉'
					},
					{
    
    
						id: 2,
						name: '打豆豆'
					}

				],
				content: ''
			};
		},
		methods: {
    
    
			changeAct(item) {
    
    
				// 激活样式是当前点击的对应下标--list中对应id
				this.act = item.id;

				// 可以根据点击事件改变内容
				this.content = item
			}
		},
		onShow() {
    
    
			// 页面默认显示的是list列表中第一条数据
			this.content = this.list[0]
		}
	}
</script>

2.3 css

<style scoped>
	.nav {
    
    
		height: 100rpx;
		display: flex;
		align-items: center;
		justify-content: space-around;
		background-color: rgba(0, 0, 0, .5);
		font-size: 30rpx;
		color: #fff;
	}
	.nav-list {
    
    
		width: 100rpx;
		height: 100%;
		margin-top: 40rpx;
		opacity: .9;
	}
	.nav-list .name {
    
    
		color: red;
	}

	.nav-list .line {
    
    
		margin-top: 10rpx;
		width: 65rpx;
		height: 4rpx;
		background-color: red;
	}

	/* 内容 */
	.content {
    
    
		margin-top: 40rpx;
		text-align: center;
	}
</style>

ending~

Guess you like

Origin blog.csdn.net/weixin_48596030/article/details/130972717