微信小程序导航栏切换页面

先看一下效果
在这里插入图片描述

wxml代码

<view class="container">
	<view class="nav">
		<view class="item {{current == '0' ? 'active' : ''}}" catchtap="onClick" data-id="0">首页</view>
		<view class="item {{current == '1' ? 'active' : ''}}" catchtap="onClick" data-id="1">分类</view>
		<view class="item {{current == '2' ? 'active' : ''}}" catchtap="onClick" data-id="2">发现</view>
		<view class="item {{current == '3' ? 'active' : ''}}" catchtap="onClick" data-id="3">收藏</view>
		<view class="item {{current == '4' ? 'active' : ''}}" catchtap="onClick" data-id="4">我的</view>
	</view>
	<view class="list">
		<block wx:for="{{newslist}}" wx:for-index="idx">
			<view class="detail" wx:if="{{idx == current}}">
				{{item.text}}
			</view>
		</block>
	</view>
</view>

在这部分代码中使用了自定义属性data-、三元运算、列表渲染和条件渲染。在这里特别要注意的是:wx:if="{{idx == current}}这个idx变量必须要在<block wx:for="{{newslist}}" wx:for-index="idx">这进行声明,如果没有声明,默认为index,也必须是index。微信官方文档中是这样写的:使用 wx:for-index 可以指定数组当前下标的变量名 默认数组的当前项的下标变量名默认为 index。

wxss代码

page{
  width: 100%;
  height: 100%;
}
.container{
  display: flex;
  flex-direction: column;
  height: 100%;
}

.nav{
  width: 100%;
  height: 100rpx;
  background-color: skyblue;
  display: flex;
  flex-direction: row;
  justify-content: space-around;
}

.item{
  font-size: 32rpx;
  color: #fff;
  height: 50rpx;
  width: 100rpx;
  line-height: 50rpx;
  align-self: center;
  text-align: center;
}

.active{
  background-color: darkgray;
  border-radius: 10rpx;
}

.list{
  width: 100%;
  height: 100%;
  display: flex;
  background-color: pink;
}

.detail{
  margin: auto;
}

js代码

data: {
    current:0,
    newslist:[{
        text:'这是首页界面内容'
      },{
        text:'这是分类界面内容'
      },{
        text:'这是发现界面内容'
      },{
        text:'这是收藏界面内容'
      },{
        text:'这是我的界面内容'
      }
    ]
  },

  onClick:function(event){
    var index = event.currentTarget.dataset.id;
    this.setData({
      current:index
    })
  },

点击导航按钮获取自定义属性值,并赋值于current。

其实使用轮播组件swiper也可以达到这样的效果,但是我觉得使在这样的场景使用轮播不太实际,这里就不说啦!

  • 16
    点赞
  • 102
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值