微信小程序——设置选项卡

以下图的两个文件为例

tab.js

Page({
    data:{
        activeIdx: 0,
        tabs:[
            {id:1,name:"选项卡一",content:"111111111",active:true},
            {id:2,name:"选项卡二",content:"222222222",active:false},
            {id:3,name:"选项卡三",content:"333333333",active:false},
        ]
    },
    changeItem(e){
        console.log(e)
        let activeIdx = -1
        const tabs = this.data.tabs.map((item,idx) => {
            if(e.detail.id === item.id){
                item.active = true
                activeIdx = idx
            }else{
                item.active = false
            }
            return item
        })
        this.setData({
            tabs,
            activeIdx
        })
    }
})

 tab.json

{
    "usingComponents": {
        "tabs":"/components/Tabs/Tabs"
    },
    "navigationBarTitleText": "选项卡"
}

tab.wxml

<tabs list="{
   
   {tabs}}" bindhandlechange = "changeItem">
    <view>内容如下</view>
    <view>{
   
   {tabs[activeIdx].content}}</view>
</tabs>

Tabs.js

Component({
    properties:{
        list:{
            type:Array,
            value:[]
        }
    },
    methods:{
        handleActive(e){
            console.log(e)
            this.triggerEvent("handlechange",{
                id:e.target.dataset.idkey
            })
        }
    }
})

Tabs.json

{
    "component": true,
    "usingComponents": {}
}

Tabs.wxml

<view class="tabs">
    <view class="tabs-title">
        <view 
            class="tabs-title-item {
   
   {item.active ? 'active' : ''}}" wx:for="{
   
   {list}}"
            wx:key="id"
            bindtap="handleActive"
            data-idkey="{
   
   {item.id}}"
        >
            {
   
   {item.name}}
        </view>
    </view>
    <view class="tabs-content">
        <slot></slot>
    </view>
</view>

Tabs.wxss

.tabs-title{
    display: flex;
}
.tabs-title-item{
    flex:1;
    border-bottom: 1px solid #363636;    
    padding: 6px 8px;
    text-align: center;
}
.active{
    color: red;
    font-size: 16px;
    border-bottom: 2px solid red;
}
.tabs-content{
    padding: 6px 8px;
}

运行效果

猜你喜欢

转载自blog.csdn.net/weixin_58963766/article/details/131628859