WeChatアプレットのカスタムコンポーネントタブ

1.ディレクトリ構造

ここに画像の説明を挿入します

2.タブ

<view class="item-wrap">
    <view class="item {
     
     { item.isActive?'active':'' }}"
     wx:for="{
     
     { tabBar }}" wx:key='id'
     bindtap="handleIndex" data-index="{
     
     { item.id }}"
     >
        {
   
   { item.value }}
    </view>
</view>

<view class="content">
<!-- 插槽  接受父组件里的子节点数据 -->
    <slot></slot>
</view>
.item-wrap{
    
    
    display: flex;
}

.item-wrap .item{
    
    
    flex:1;
    text-align: center;
    padding: 20rpx 0;
}

.item-wrap .item.active{
    
    
    border-bottom: 3px solid red;
}
// components/tabs/tabs.js
Component({
    
    
  /**
   * 组件的属性列表
   */
  properties: {
    
    
    tabBar:Array
  },
  methods:{
    
    
    handleIndex(e){
    
    
      // 获取点击的索引
      const {
    
     index } = e.currentTarget.dataset
      // 通过自定义事件传给父级
      this.triggerEvent('transformIndex', index)
    }
  },

})

3.親コンポーネント

<Tabs tabBar='{
     
     { tabBar }}' bind:transformIndex='handleIndex'>

    <view wx:if="{
     
     { tabBar[0].isActive }}">
        综合数据
    </view>
    <view wx:elif="{
     
     { tabBar[1].isActive }}"> 
        销量数据
    </view>
    <view wx:elif="{
     
     { tabBar[2].isActive }}">
        价格数据
    </view>

</Tabs>
// pages/index/index.js
Page({
    
    

    /**
     * 页面的初始数据
     */
    data: {
    
    
        tabBar: [
            {
    
    
                id:0,
                value: '综合',
                isActive: true
            },
            {
    
    
                id:1,
                value: '销量',
                isActive: false
            },
            {
    
    
                id:2,
                value: '价格',
                isActive: false
            }
        ]
    },
    handleIndex(e){
    
    
        // 接受tabs传过来的index
        const index = e.detail;
        const {
    
    tabBar} = this.data;
        tabBar.forEach(v=>v.id === index ? v.isActive = true: v.isActive = false)
        this.setData({
    
    
            tabBar
        })
    }
})
{
    
    
  "usingComponents": {
    
    
    "Tabs":"/components/tabs/tabs"
  }
}
3.効果

ここに画像の説明を挿入します

おすすめ

転載: blog.csdn.net/gklcsdn/article/details/111629703