Uni-app/Vue实现微信小程序tab导航栏下划线切换动画

本文介绍移动端中常用的tab导航栏下划线动画,仅针对点击切换不支持滑动切换 html部分:

<view class="tab-wrap">
		<view style="display: flex;width: 100vw;">
			<view
				class="menu-box"
				:class="activeindex === menuindex? active :  "
				@tap="choosemenu(menuindex)"
				v-for="(menu,menuindex) in menulist"
				:key="menuindex">
				{
         
  {menu}}
			</view>
			<view class="bottom_line" :style="`left:${left}px`"></view>
		</view>
	</view>

CSS部分

.tab-wrap {
          
   
	position: relative;
	height: 160rpx;
	display: flex;
	align-items: flex-end;
}
.menu-box {
          
   
	width: 15%;
	height: 80rpx;
	font-size: 16px;
	display:flex;
	flex-direction: column;
	align-items: center;
}
.active {
          
   
	font-weight:bold
}
.bottom_line {
          
   
	width: 40rpx;
	height: 4rpx;
	background-color: #007AFF;
	position: absolute;
	bottom: 8rpx;
	transition: all .2s linear;
}

js部分

export default {
          
   
		data() {
          
   
			return {
          
   
				activeindex: 0,
				menulist: [商品, 评价, 店铺],
				left: 0
			}
		},
		methods: {
          
   
			choosemenu(menuindex) {
          
   
				this.activeindex = menuindex
				//做一个短暂的延迟保证选中的tab是用户点击的tab
				setTimeout(()=>{
          
   
					this.lineChange()
				},100) 		
			},
			lineChange() {
          
   
				const query = uni.createSelectorQuery()
				query.select(.active).boundingClientRect().exec(res => {
          
   
					//计算出当前选中的tab距离窗口左侧距离加上tab选项宽度减去下划线宽度除以2(目的:让下划线居中)
					this.left = res[0].left + uni.upx2px(36)	
				})
			}
	}
}
经验分享 程序员 微信小程序 职场和发展