my-tab.js

// component/my-tab/my-tab.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    tabArr:{
      type:Array,
      value:[]
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    currentIndex:0
  },

  /**
   * 组件的方法列表
   */
  methods: {
    tabClick(e){
      this.setData({
        currentIndex:e.currentTarget.dataset.index
      })
      console.log(this.data.currentIndex);
      this.triggerEvent('tab',{
        tab_index: this.data.currentIndex,
        title: this.data.tabArr[this.data.currentIndex]
      })
    }
  }
})

my-tab.wxss

/* component/my-tab/my-tab.wxss */
.tab-box {
  display: flex;
  background: rgb(240, 239, 239);
  height: 100rpx;
  line-height: 100rpx;
}
.tab-item {
  flex: 1;
  text-align: center;
}
.tab-box .active {
  color: red;
}

my-tab.wxml

<!--component/my-tab/my-tab.wxml-->
<view class="tab-box">
  <block wx:for="{{tabArr}}" wx:key="index">
    <view class="tab-item {{currentIndex == index?'active':''}}" bindtap="tabClick" data-index="{{index}}">
      <text>{{item}}</text>
    </view>
  </block>
</view>

在页面中的·使用

<!--index.wxml-->
<view class="container">
   <!-- tab标签栏实战 -->
   <my-tab bindtab="itemClick" tabArr="{{cates}}"></my-tab>
</view>
//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    title:"这是页面传的数据",
    cates:['推荐','热门','时尚','娱乐']
  },
  onLoad: function () {
    
  },
  search:function(e){
    console.log(e.detail.searchText);
  },
  itemClick: function(e){
    console.log(e.detail);
  }
})
Logo

欢迎加入 MCP 技术社区!与志同道合者携手前行,一同解锁 MCP 技术的无限可能!

更多推荐