npm install 安装 vant weapp, mobx 的包,安装好了进行构建Npm (工具--构建npm)
npm install vant-weapp npm install --save mobx-miniprogram@4.13.2 mobx-miniprogram-bindings@1.2.1
解释一下:这里的mobx-miniprogram 是 实例化, mobx-miniprogram-bindings是具体操作
app.json: (目的是 pages 创建文件夹 和 tabBar低版本兼容,特别是定制化的 custom:true)
{ "pages": [ "pages/home/home", "pages/user/user", "pages/index/index", "pages/logs/logs" ], "window": { "navigationBarTextStyle": "black", "navigationBarTitleText": "Weixin", "navigationBarBackgroundColor": "#ffffff" }, "tabBar": { "custom": true, "list": [{ "pagePath": "pages/home/home", "text": "首页" }, { "pagePath": "pages/user/user", "text": "我的" }] }, "usingComponents": { "van-button":"@vant/weapp/button/index" }, "componentFramework": "glass-easel", "sitemapLocation": "sitemap.json", "lazyCodeLoading": "requiredComponents" }
创建 mobx 的全局状态管理:
创建store文件夹下的store.js
以下的目的是实例化Mobx: 并且设置参数的值和方法改变的值
import { observable, action } from 'mobx-miniprogram'; export const store = observable({ activeTabBarIndex: 0, updateActiveTabBarIndex: action(function(index) { this.activeTabBarIndex = index; }) });
创建自定义的tabbar组件:
wxml:
<van-tabbar active="{{active}}" bind:change="onChange"> <van-tabbar-item wx:for="{{ list }}" wx:key="index" icon="{{item.icon}}" >{{item.text}}</van-tabbar-item> </van-tabbar>
index.js (引入mobx,并且开始设置全局共享的数据)
import { storeBindingsBehavior } from 'mobx-miniprogram-bindings'; import { store } from '../store/store'; Component({ options: { styleIsolation: 'shared' }, behaviors: [storeBindingsBehavior], storeBindings: { store, fields: { active: 'activeTabBarIndex' }, actions: { updateActive: 'updateActiveTabBarIndex' } }, data: { icon: { normal: 'https://img.yzcdn.cn/vant/user-inactive.png', active: 'https://img.yzcdn.cn/vant/user-active.png', }, list: [{ pagePath: '/pages/home/home', text: '首页', icon: 'home-o' }, { pagePath: '/pages/user/user', text: '我的', icon: 'user-o' }] }, methods: { onChange(event) { this.updateActive(event.detail); // mobx更改值!!! wx.switchTab({ url: this.data.list[event.detail].pagePath, }); }, } });
index.json:
{ "component": true, "usingComponents": { "van-tabbar": "@vant/weapp/tabbar/index", "van-tabbar-item": "@vant/weapp/tabbar-item/index" } }
最后展示: