自定义 tabBar 效果
自定义 tabBar 在
app.json
中的tabBar
里设置custom
为true
就可以关闭原生 tabBar。
-
开启自定义 tabBar
原生的 tabBar 内容不删除,兼容低版本。
{ // 注册vant组件 "usingComponents": { "van-tabbar": "@vant/weapp/tabbar/index", "van-tabbar-item": "@vant/weapp/tabbar-item/index" }, "tabBar": { // 开启自定义tabBar "custom": true, "list": [...] } }
-
tabBar
选中下标写在Store.store.js
中。解决切换 tabBar 时,下标不正确的问题。
/* Store.store.js */ import { observable, action } from 'mobx-miniprogram' export const store = observable({ // tabBar选中的下标 activeIndex: 0, // 修改tabBar选中的下标 updateActiveIndex: action( function (index) { this.activeIndex = index }) })
-
在根目录下创建
custom-tab-bar
组件,用来设置自定义 tabBar。<!-- custom-tab-bar/index.wxml --> <van-tabbar active="{ { activeIndex }}" bind:change="onChange"> <van-tabbar-item wx:for="{ {list}}" wx:key="index" info="{ {item.info && item.info}}"> <image slot="icon" src="{ { item.iconPath }}" mode="aspectFit" style="width: 25px; height: 25px;" /> <image slot="icon-active" src="{ { item.selectedIconPath }}" mode="aspectFit" style="width: 25px; height: 25px;" /> { {item.text}} </van-tabbar-item> </van-tabbar>
// custom-tab-bar/index.js import { storeBindingsBehavior } from 'mobx-miniprogram-bindings' import { store } from '../Store/store' Component({ // 1.混入Store定义好的属性和方法 behaviors: [storeBindingsBehavior], storeBindings: { store, fields: ['activeIndex'], actions: ['updateActiveIndex'] }, // 组件的属性列表 properties: { }, data: { // tabBar列表 list: [ { pagePath: "/pages/index/index", text: "首页", iconPath: "/images/home.png", selectedIconPath: "/images/home-active.png" }, { "pagePath": "/pages/message/message", "text": "信息", "iconPath": "/images/message.png", "selectedIconPath": "/images/message-active.png" }, { "pagePath": "/pages/contact/contact", "text": "联系我们", info: 3, "iconPath": "/images/contact.png", "selectedIconPath": "/images/contact-active.png" } ] }, methods: { // 2.切换tabBar onChange(event) { // 2.1更新下标 this.updateActiveIndex(event.detail) // 2.2跳转路由 wx.switchTab({ url: this.data.list[event.detail].pagePath, }) }, } })