简要
微信小程序中有时需要进行全局状态管理,这个时候就需要用到Mobx.下面我们来看一下在小程序中是如何使用Mobx的
安装
pnpm i mobx-miniprogram@4.13.2 mobx-miniprogram-bindings@1.2.1
或
npm i mobx-miniprogram@4.13.2 mobx-miniprogram-bindings@1.2.1
或
yarn add mobx-miniprogram@4.13.2 mobx-miniprogram-bindings@1.2.1
配置
根目录下新建store文件夹,新建store.js文件
import { observable, action } from 'mobx-miniprogram'export const store = observable({//数据字段numA: 1,numB: 2,//计算属性get sum() {return this.numA + this.numB},//actions方法updateNumA: action(function (step) {this.numA += step}),updateNumB: action(function (step) {this.numB += step;})
})
页面中如何使用
// pages/notice/notice.js
import { createStoreBindings } from 'mobx-miniprogram-bindings'
import { store } from '../../store/store'Page({//点击页面按钮触发的函数handler() {//获取numA的值console.log(this.data.numA);//修改numA的值this.updateNumA(this.data.numA + 1)},onLoad(options) {this.storeBindings = createStoreBindings(this, {store,//指定使用的仓库(此处使用es6语法)fields: ['numA', 'numB', 'sum'],//指定字段actions: ['updateNumA', 'updateNumB']//指定方法})},onUnload() {//页面卸载时需要卸载仓库this.storeBindings.destroyStoreBindings()}
})
组件中如何使用
import { storeBindingsBehavior } from 'mobx-miniprogram-bindings'
import { store } from '../../store/store'
Component({behaviors: [storeBindingsBehavior],storeBindings: {store,fields: {numA: () => store.numA,//绑定字段的第一种方式numB: (store) => store.numB,//绑定字段的第二种方式sum: 'sum'//绑定字段的第三种方式},actions: {//指定要绑定的方法updateNumA: 'updateNumA'}}
})