小程序-可通用的目录栏组件

原理

  • 子层向父层传递数据和绑定点击按钮显示不同的数据
  • 这里核心是点击显示数据我们采用了子层向父层:this.triggerEvent('tabclick', data, {})
  • 父层接收:bindtabclick="handleTabClick"

设计父层

父层wxml

<w-tab-control titles="{{titles}}" bindtabclick="handleTabClick"class="{{isTabFixed?'fixed':''}}" />
<w-tab-control wx:if="{{isTabFixed}}" />

父层js

const types = ['pop', 'new', 'sell']
Page({
    /**
    * 页面的初始数据
    */
    data: {
        currentType: 'pop',
    },
   
    handleTabClick(event) {
        //console.log(event)
        //取出index
        const index = event.detail.index;
        console.log(index);
        //修改currentType
        const type = types[index]
        this.setData({
            currentType: type
            //currenttype:types[index]
        })
    }
})

设计子层

子层wxml

<view class="tab-control">
    <block wx:for="{{titles}}" wx:key="{{index}}">
        <view class='tab-item {{currentIndex == index ?"active":" "}}' bindtap="itemClick" data-index="{{index}}">
            <text>{{item}}</text>
        </view>
    </block>
</view>

子层wxss

.tab-control {
    display: flex;
    height: 88rpx;
    line-height: 88rpx;
    background: #fff;
    padding-bottom: 10rpx;
    /* background: orange; */
}

.tab-item {
    flex: 1;
    text-align: center;
}

.active {
    color:#1296db;
}
.active text{
    padding: 10rpx 10rpx;
    border-bottom: 6rpx solid #1296db;
}

子层js

Component({
    /**
    * 组件的属性列表
    */
    properties: {
        titles: {
            type: Array,
            value: []
        }
    },
    /**
    * 组件的初始数据
    */
    data: {
        currentIndex: 0
    },

    /**
    * 组件的方法列表
    */
    methods: {
        itemClick(event) {
            //  获取传入的index
            const index = event.currentTarget.dataset.index;
            // console.log("--------", index)
            //改变原有记录的currentIndex
            this.setData({
                currentIndex: index
            })
            //发出时间
            const data = {
                index: this.data.currentIndex
            }
            //发出自定义事件
            this.triggerEvent('tabclick', data, {})
        }
    }
})

图片效果

thisisimage

原文地址:https://www.cnblogs.com/dongxuelove/p/13046547.html