微信小程序 自定义顶部Tab栏
需求:微信小程序在页面顶部增加Tab栏功能,方便切换功能模块。
开始: 首先生成微信小程序开发项目文件,同时打算将其Tab功能封装成组件,方便后续项目复用。
所以将其代码放在小程序项目文件下面的components下。
WXML
<view class="tabs">
<view class="tabs_title">
<view wx:for="{{tabList}}" wx:key="id" class="title_item {{item.isActive?'active':''}}" bindtap="handleItemTap"
data-index="{{index}}">
<view style="margin-bottom:5rpx">{{item.value}}</view>
<view style="width:20px" class="{{item.isActive?'active1':''}}"></view>
</view>
</view>
<view class="tabs_content">
<slot></slot>
</view>
</view>
遍历自定义源数组数据,动态绑定类名实现选中和非选中的效果
WXSS
.tabs{
position: fixed;
top: 0;
width: 100vw;
background-color: #fff;
z-index: 99;
border-bottom: 1px solid #efefef;
padding-bottom: 20rpx;
}
.tabs_title{
/* width: 400rpx; */
width: 70%;
display: flex;
font-size: 28rpx;
padding: 0 20rpx;
}
.title_item{
color: #999;
padding: 15rpx 0;
display: flex;
flex: 1;
flex-flow: column nowrap;
justify-content: center;
align-items: center;
}
.active{
/* color:#ED8137; */
color: #000000;
font-size: 18px;
font-weight: 800;
}
.active1{
/* color:#ED8137; */
color: #000000;
font-size: 18px;
font-weight: 800;
border-bottom: 8rpx solid #ED8137;
border-radius: 4px;
}
自定义样式文件,可以随着项目具体需求,进行更改
JSON
{
“component”: true,
“usingComponents”: {}
}
声明为为组件
JS
var App = getApp();
Component({
/**
* 组件的属性列表
*/
properties: {
tabList:Object
},
/**
* 组件的初始数据
*/
data: {
},
/**
* 组件的方法列表
*/
methods: {
handleItemTap(e){
// 获取索引
const {index} = e.currentTarget.dataset;
// 触发 父组件的事件
this.triggerEvent("tabsItemChange",{index})
}
}
})
页面调用组件
引入组件
<Tab tabList="{{tabList}}" bindtabsItemChange="tabsItemChange">
</Tab>
页面调用组件
tabList: [
{
id: 0,
value: '活动大厅',
isActive: true
},
{
id: 1,
value: '我的活动',
isActive: false
},
{
id: 2,
value: '消息',
isActive: false
},
],
绑定源数组
```javascript
tabsItemChange(e) {
}
监听tabItme切换事件