微信小程序顶部tab

tab子组件

<view class="tab">
 <view class="tab-title">

  <view wx:for="{{tabs}}"
        wx:key="id"
        class="title-item {{item.isActive ? 'active' : ''}}"
        bindtap="handleItem"
        data-index="{{index}}">

        {{item.name}}

  </view>
 </view>
 <view class="tab-content">
  内容
 </view>
</view>
.tab{
  margin-top: 20rpx;
}
.tab-title{
  display: flex;
}
.title-item{
  display: flex;
  flex: 1;
  justify-content: center;
  align-items: center;
}
.active{
  color: red;
  border-bottom: red 6rpx solid;
}

js

Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    tabs:[
      {
        id:0,
        name:"首页",
        isActive:true
      },
      {
        id:1,
        name:"原创",
        isActive:false
      },
      {
        id:2,
        name:"分类",
        isActive:false
      },
      {
        id:3,
        name:"关于",
        isActive:false
      },
    ]
  },

  /**
   * 组件的方法列表
   */
  methods: {
    handleItem(e) {
      // 获取索引
      const index = e.currentTarget.dataset.index
      // 拿到数组
      const {tabs} = this.data
      // 遍历数组,处理数据
      tabs.forEach((item,i) => {
        if (i === index) {
          item.isActive = true
        } else {
          item.isActive = false
        }
        // 更新数组
        this.setData({
          tabs
        })
      })
    }
  }
})

展示对应的数据即可.

猜你喜欢

转载自www.cnblogs.com/zhaohui-116/p/13365796.html