微信小程序tab切换组件

tab

html

<!--components/Tab/tab.wxml-->
<view class="tabs">
    <view class="tabs_title">
        <view
         wx:for="{{tabList}}"
         wx:key="id"
         class="title_item  {{item.isActive?'active':''}}"
         bindtap="handleItemTap"
         data-index="{{index}}"
        >
            {{item.value}}
        </view>
    </view>
    <view class="tabs_content">
        <slot></slot>
    </view>
</view>

js

// components/Tab/tab.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    tabList:Object
  },

  /**
   * 组件的初始数据
   */
  data: {

  },

  /**
   * 组件的方法列表
   */
  methods: {
    handleItemTap(e){
      // 获取索引
      const {index} = e.currentTarget.dataset;
      // 触发 父组件的事件
      this.triggerEvent("tabsItemChange",{index})
    }
  }
})

css

/* components/Tab/tab.wxss */

.tabs_title{
    background-color: #fff;
    display: flex;
    font-size: 28rpx;
    padding: 0 20rpx;
}
.title_item{
    color: #999;
    padding: 15rpx 0;
    display: flex;
    flex: 1;
    justify-content: center;
    align-items: center;
}
.active{
    color:#ED8137;
    border-bottom: 5rpx solid #ED8137;
}

上面的代码是组件里的代码

下面是使用组件

json页面调用组件

{
  "usingComponents": {
    "Tab":"../../components/Tab/tab" //组件路径
  }
}

HTML

<Tab tabList="{{tabList}}" bindtabsItemChange="tabsItemChange">
//这里是页面内容
</Tab>

js

Page({
  data: {
    tabList:[
      {
        id:0,
        value:'全部订单',
        isActive:true
      },
      
      {
        id:1,
        value:'待支付',
        isActive:false
      },
      {
        id:2,
        value:'待接单',
        isActive:false
      },
      {
        id:3,
        value:'进行中',
        isActive:false
      },
      {
        id:4,
        value:'已完成',
        isActive:false
      },
      {
        id:5,
        value:'已取消',
        isActive:false
      },
    ],
  },// 根据标题索引来激活选中 标题数组
   changeTitleByIndex(index){
    let {tabList}=this.data
    tabList.forEach((v,i) => i===index? v.isActive = true:v.isActive = false);
    this.setData({
      tabList
    })
  },
  tabsItemChange(e){
    // 1 获取被点击的标题索引
    const {index}=e.detail
    this.changeTitleByIndex(index)
  },