小程序 tabbar 功能切换 组件封装

<!--components/Tabs/Tabs.wxml-->
<view class="tabs">
<view class="tabs_title">
<view
wx:for="{{tabs}}"
wx:key="id"
class="title_item {{item.isActive ? 'active' : ''}}"
bindtap="handleItemTap"
data-index="{{index}}"
>
{{item.value}}
</view>
</view>
<view class="tabs_content">
<slot></slot>
</view>
</view>
/* components/Tabs/Tabs.wxss */
.tabs{}
.tabs_title{
display: flex;
}
.title_item{
display: flex;
justify-content: center;
align-items: center;
flex: 1;
padding: 15rpx 0;
}
.active{
color: var(--themeColor);
border-bottom: 5rpx solid currentColor;
}
.tabs_content{
}
// components/Tabs/Tabs.js
Component({
/**
* 组件的属性列表
*/
properties: {
tabs:{
type:Array,
value:[]
}
},
/**
* 组件的初始数据
*/
data: {
},
/**
* 组件的方法列表
*/
methods: {
// 点击事件
handleItemTap(e){
// 1 获取点击的索引
const {index} = e.currentTarget.dataset;
// console.log(index)
// 2 触发 父组件中的事件 自定义
this.triggerEvent("tabsItemChange",{index})
}
}
})
<Tabs tabs="{{tabs}}" bindtabsItemChange="handleTabsItemChange">
</Tabs>
// 标题点击
handleTabsItemChange(e){
// 1 获取被点击的标题索引
const {index} = e.detail
// console.log(index)
this.changeTitleByIndex(index)
},
// 点击自定义图片组件
handleRemoveImg(e){
// 2 获取被点击组件的索引
const {index} = e.currentTarget.dataset;
// console.log(index)
// 3 获取data 中的图片数组
let {chooseImgs} = this.data;
// 4 删除元素
chooseImgs.splice(index,1);
this.setData({chooseImgs})
},
// 根据标题索引来激活选中的 标题数组
changeTitleByIndex(index){
// 2 修改源数据
let {tabs} = this.data;
tabs.forEach( (v,i)=>i === index ? v.isActive = true : v.isActive = false )
// 3 赋值到 data 中
this.setData({
tabs
})
},
我是Eric,手机号是13522679763

浙公网安备 33010602011771号