微信小程序使用自定义Tabbar
(1)在原本的全局配置app.json的底部导航上面部分添加"custom": true,
"tabBar": {
"custom": true, // 需要添加的部分
"color": "#cccccc",
"selectedColor": "#000000",
"backgroundColor": "#ffffff",
"borderStyle": "black",
"list": [
{
"pagePath": "pages/home/home",
"text": "home",
"iconPath": "/tabs/home.png",
"selectedIconPath": "/tabs/home-active.png"
},
{
"pagePath": "pages/message/message",
"text": "message",
"iconPath": "/tabs/message.png",
"selectedIconPath": "/tabs/message-active.png"
},
{
"pagePath": "pages/profile/profile",
"text": "profile",
"iconPath": "/tabs/profile.png",
"selectedIconPath": "/tabs/profile-active.png"
}
]
},
(2)在微信官方文档.小程序中搜索"自定义 tabBar",选择查看示例代码(在开发者公众中打开)
(3)选择导入
(3)把custom-tab-bar复制到自己项目的根目录下面(选择在硬盘中打开去复制)
(4)把原来app.json中的tabBar中的list复制到custom-tab-bar的index.js中,【注】:复制过来的list中的papePath中的路径前要加/:
Component({
data: {
selected: 0,
color: "#7A7E83",
selectedColor: "#3cc51f",
list: [
{
"pagePath": "/pages/home/home",
"text": "home",
"iconPath": "/tabs/home.png",
"selectedIconPath": "/tabs/home-active.png"
},
{
"pagePath": "/pages/message/message",
"text": "message",
"iconPath": "/tabs/message.png",
"selectedIconPath": "/tabs/message-active.png"
},
{
"pagePath": "/pages/profile/profile",
"text": "profile",
"iconPath": "/tabs/profile.png",
"selectedIconPath": "/tabs/profile-active.png"
}
]
},
attached() {
},
methods: {
}
})
(5)在custom-tab-bar的index.json文件中引入第三方组件vant-weapp(按需引入)来自定义底部导航:
{
"component": true,
"usingComponents": {
"van-tabbar": "/vant/tabbar/index",
"van-tabbar-item": "/vant/tabbar-item/index"
}
}
(6)在custom-tab-bar的index.wxml中复制组件biang改写代码:
selected就是指被选中的底部导航tab的索引:
<van-tabbar active="{{ selected }}" bind:change="switchTab">
<van-tabbar-item wx:for="{{list}}" wx:key="index">
<image
slot="icon"
src="{{ item.iconPath }}"
mode="aspectFit"
style="width: 30px; height: 18px;"
/>
<image
slot="icon-active"
src="{{ item.selectedIconPath }}"
mode="aspectFit"
style="width: 30px; height: 18px;"
/>
{{item.text}}
</van-tabbar-item>
</van-tabbar>
(7)实现点击跳转页面和样式改变:在custom-tab-bar的index.js中编写methods方法:
switchTab(e) {
// console.log(e);
// 有bug,要点两下才跳转
// this.setData({
// selected: e.detail
// })
wx.switchTab({
url:this.data.list[e.detail].pagePath
})
}
【注】:还要在每个要跳转到的页面的.js文件中的 onShow方法(生命周期函数–监听页面显示)中编写代码:
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
if(typeof this.getTabBar === 'function' && this.getTabBar()){
this.getTabBar().setData({
selected: 0 // 索引为0,是第一个tab
})
}
}
【注】:编写 tabBar 代码:
用自定义组件的方式编写即可,该自定义组件完全接管 tabBar 的渲染。另外,自定义组件新增 getTabBar 接口,可获取当前页面下的自定义 tabBar 组件实例。
这样自定义的tabbar底部导航跳转就完成了!