本文只是一次代码记录
最终效果如下:
- 根目录创建
custom-tab-bar文件夹,创建component
index.js
// custom-tab-bar/index.js
Component({
/**
* 组件的属性列表
*/
properties: {
},
/**
* 组件的初始数据
*/
data: {
selected: 0,
color: "#ffffff",
selectedColor: "#EE3D42",
listTab: [
{
pagePath: "/pages/index/index",
text: "导航1"
},
{
pagePath: "/pages/home/index",
text: "导航2"
}
]
},
/**
* 组件的方法列表
*/
methods: {
switchTab(e) {
const data = e.currentTarget.dataset;
const url = data.path;
wx.switchTab({ url });
}
}
})
index.json
{
"component": true,
}
index.wxml
<!--custom-tab-bar/index.wxml-->
<view class="tab-bar">
<image class="tab-bar-bg" mode="scaleToFill" src="/assets/tabbar_bg.png"></image>
<view class="tab-bar-content">
<view wx:for="{{listTab}}" wx:key="index" class="tab-bar-item" data-path="{{item.pagePath}}" data-index="{{index}}" bindtap="switchTab">
<view style="color: {{selected === index ? selectedColor : color}}">{{item.text}}</view>
</view>
</view>
</view>
index.wxss
/* custom-tab-bar/index.wxss */
.tab-bar {
position: fixed;
bottom: 10rpx;
left: 0;
right: 0;
height: 100rpx;
width: 100%;
display: flex;
flex-direction: row;
justify-content: center;
padding-bottom: env(safe-area-inset-bottom);
}
.tab-bar-bg {
width: 70%;
height: 100rpx;
position: fixed;
justify-content: center;
}
.tab-bar-content {
height: 100rpx;
width: 40%;
display: flex;
}
.tab-bar-item {
flex: 1;
text-align: center;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
position: relative;
}
.tab-bar-item view {
font-size: 40rpx;
font-weight: 700;
}
- 在
app.json添加tabbar,"custom": true标识自定义tabbar
"tabBar": {
"custom": true,
"color": "#999999",
"selectedColor": "#EE3D42",
"list": [
{
"pagePath": "pages/index/index",
"text": "导航1"
},
{
"pagePath": "pages/home/index",
"text": "导航2"
}
]
}
- 在需要显示的
*.js(如:pages/index/index.js,pages/home/index.js)中添加
/**
* 生命周期函数--监听页面显示
*/
onShow() {
if (typeof this.getTabBar === 'function' && this.getTabBar()) {
this.getTabBar().setData({
selected: 0 //0,1 0-导航1 1-导航1
})
}
},