微信小程序navbar导航切换实现
业务场景:点击navbar切换显示不同内容
wxml代码
<view class="main">
<view class="movie-container">
<!-- 导航栏 -->
<view class="navbar">
<block wx:for="{{navbarTitle}}" wx:key="index">
<view class="navbar-item {{navbarActiveIndex === index ? 'navbar-item-active' : ''}}"
data-navbar-index="{{index}}" catchtap="onNavBarTap">
<text>{{item}}</text>
</view>
</block>
</view>
<view class="movie-content-wrapper">
<view wx:if="{{navbarActiveIndex == 0}}">
<recom></recom>
</view>
<view wx:elif="{{navbarActiveIndex == 1}}">
<office></office>
</view>
</view>
</view>
</view>
wxss代码
/* nvabar */
.main {
display: flex;
justify-content: center;
}
.movie-container {
display: flex;
flex-direction: column;
width: 90%;
margin-top: 20rpx;
background-color: #FFF;
padding-bottom: 50rpx;
border-radius: 20rpx;
}
.navbar {
display: flex;
flex-direction: row;
width: 100%;
height: 50px;
text-align: center;
color: #A8A8A8;
font-size: 15px;
box-sizing: border-box;
background-color: #FFF;
border-bottom: 1rpx solid #DFDFDF;
}
.navbar-item {
flex: 1;
padding: 26rpx 0px;
}
.movie-content-wrapper {
min-height: 550rpx;
}
.navbar-item-active {
transition: all .3s ease-out .1s;
border-bottom: 6rpx solid #28b2e9;
color: #28b2e9;
}
js代码
data: {
currentIndex: 0,
},
onNavBarTap: function (event) {
// 获取点击的navbar的index
let navbarTapIndex = event.currentTarget.dataset.navbarIndex;
// 设置data属性中的navbarActiveIndex为当前点击的navbar
this.setData({
navbarActiveIndex: navbarTapIndex
})
console.log(this)
}