微信小程序(tab栏的封装和使用)

本文详细介绍了如何在微信小程序中封装自定义tab栏组件,包括`my-tab.js`、`my-tab.wxss`和`my-tab.wxml`的代码实现,并展示了在实际页面中的应用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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);
  }
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值