实现微信小程序自定义选项卡组件以及tabs悬浮置顶

 我是将选项卡单独抽取出来做一个自定义组件,组件内用slot插槽来改变内容 ,slot要设置成scroller-view才可以实现tabs固定而下方滑动。切换选项卡,只需要每次判断点击id,就可以切换内容。

//cpn-tabs.wxml
​
<view class="cpn-tab">
  <view class="tab-control">
    <view class="tab-group {{item.isActive?'active':''}}"
    wx:for="{{titles}}"
    wx:key="id"
    bind:tap="handleTap"
    data-index="{{index}}"
    >
      <text>{{item.value}}</text>
    </view>
  </view>

  <view class="tab-content">
    <scroll-view class="scroll-view" scroll-y>//这里要用到scroll-view来实现tabs悬浮,tabs以下滑动                        
      <slot></slot>
    </scroll-view>
  </view>
</view>

​
//组件的wxss代码
page{
    height: 100vh;
    
}
.cpn-tab{
    height: 100vh;
}
.tab-control{
    display: flex;
    height: 90rpx;
}
.tab-group{
    
    flex: 1;
    padding: 10rpx;
    text-align: center;
    justify-content: center;
    align-items: center;
    
}
.active{
    color: #e4b04b;
    
}
.active text{
    padding: 10rpx;
    border-bottom: #e4b04b solid 6rpx;
}
.scroll-view{
    height: calc( 100vh - 90rpx );//这一步很关键,设置tabs以下高度
}
//组件的js页面
Component({
  data: {
    isActive:false
  },
  properties: {
    titles:{
      type:Array,
      value:[]
    }
  },
  methods: {
    handleTap(e){
      const index=e.currentTarget.dataset.index;
      this.setData({
        currentIndex:index
      });
      this.triggerEvent("tabsItemChange",{index});//将每次监听到的点击事件传给引用页面
    }
  }
})

 

 

 这是引用选项卡组件的wxml页面以及js页面

//js
data: {
		titles:[
			{
				id:0,
				value:"a",
				isActive:true
			},
			{
				id:1,
				value:"b",
				isActive:false
			},
			{
				id:2,
				value:"c",
				isActive:false
			}
		]
},
handleTabsItemChange(e){
		const {index}=e.detail;//拿到每次点击事件的index,对isActive进行设置

		let {titles}=this.data;
		titles.forEach((v,i)=>i===index?v.isActive=true:v.isActive=false);
		this.setData({
			titles
		})
	},

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值