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

先看一下效果
微信小程序导航栏切换页面_第1张图片

wxml代码


	
		{{current == '0' ? 'active' : ''}}" catchtap="onClick" data-id="0">首页
		{{current == '1' ? 'active' : ''}}" catchtap="onClick" data-id="1">分类
		{{current == '2' ? 'active' : ''}}" catchtap="onClick" data-id="2">发现
		{{current == '3' ? 'active' : ''}}" catchtap="onClick" data-id="3">收藏
		{{current == '4' ? 'active' : ''}}" catchtap="onClick" data-id="4">我的
	
	
		{{newslist}}" wx:for-index="idx">
			{{idx == current}}">
				{{item.text}}
			
		
	

在这部分代码中使用了自定义属性data-、三元运算、列表渲染和条件渲染。在这里特别要注意的是:wx:if="{{idx == current}}这个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也可以达到这样的效果,但是我觉得使在这样的场景使用轮播不太实际,这里就不说啦!

你可能感兴趣的:(小程序)