github 地址:
https://github.com/wechat-miniprogram/mobx-miniprogram-bindings
。
npm install --save mobx-miniprogram mobx-miniprogram-bindings
安装 mobx-miniprogram
和 mobx-miniprogram-bindings
。工具 --> 构建 npm
完成构建。在小程序根目录下新建 store.js
文件,创建 MobX Store。
// store.js
import { observable, action } from "mobx-miniprogram";export const store = observable({// 数据字段numA: 1,numB: 2,// 计算属性get sum() {return this.numA + this.numB;},// actionsupdateNumA: action(function () {this.numA = 3;}),
});
将页面、自定义组件和 store 绑定有两种方式: behavior 绑定和手工绑定 。
import { storeBindingsBehavior } from "mobx-miniprogram-bindings";
Component({behaviors: [storeBindingsBehavior],storeBindings: {// 绑定配置},// 也可以把 storeBindings 设置为一个数组,可以同时绑定多个 storestoreBindings: [{// 绑定配置 1},{// 绑定配置 2},],
})
在页面 onUnload 或自定义组件 detached 时一定要调用清理函数,否则将导致内存泄漏。
import { createStoreBindings } from "mobx-miniprogram-bindings";Page({onLoad() {this.storeBindings = createStoreBindings(this, {// 绑定配置});},onUnload() {this.storeBindings.destroyStoreBindings();},
});
无论使用哪种绑定方式,都必须提供一个绑定配置对象。这个对象包含以下字段:
['numA', 'numB']
。{ a: 'numA', b: 'numB' }
,此时 this.data.a === store.numA
,this.data.b === store.numB
。{ a: () => store.numA, b: () => anotherStore.numB }
,此时 this.data.a === store.numA
,this.data.b === anotherStore.numB
。['update']
,此时 this.update === store.update
。{ buttonTap: 'update' }
,此时 this.buttonTap === store.update
。为了提升性能,在 store 中的字段被更新后,并不会立刻同步更新到 this.data 上,而是等到下个 wx.nextTick 调用时才更新,这样可以显著减少 setData 的调用次数。
如果需要立刻更新,可以在 behavior 绑定中调用this.updateStoreBindings()
,或者在手工绑定中调用this.storeBindings.updateStoreBindings()
。
如果只是更新对象中的一部分,是不会引发界面变化的。
例如:this.someObject.someField = "xxx";
是不会触发界面更新的,可以改成this.someObject = Object.assign({}, this.someObject, { someField: "xxx" });
。
import { storeBindingsBehavior } from "mobx-miniprogram-bindings";
import { store } from "../../store/store";Component({behaviors: [storeBindingsBehavior],storeBindings: {store,fields: {numA: "numA",numB: "numB",sum: "sum",},actions: {updateNumA: "updateNumA",},},methods: {myMethod() {this.updateNumA()wx.nextTick(() => {const A = this.data.numA; // 3const B = this.data.numB; // 2const C = this.data.sum; // 5})},},
});
小程序基础库版本 2.9.2 以上,可以直接像 Component 构造器那样引入 behaviors 。
import { createStoreBindings } from "mobx-miniprogram-bindings";
import { store } from "../../store/store";Page({onLoad() {this.storeBindings = createStoreBindings(this, {store,fields: ["numA", "numB", "sum"],actions: ["updateNumA"],});wx.nextTick(() => {const A = this.data.numA; // 1const B = this.data.numB; // 2const C = this.data.sum; // 3})},onUnload() {this.storeBindings.destroyStoreBindings();},myMethod() {this.updateNumA()wx.nextTick(() => {const A = this.data.numA; // 3const B = this.data.numB; // 2const C = this.data.sum; // 5})},
})
上一篇:【Android安全】Android 应用组件 | Android 四大组件
下一篇:节后海南离岛难:进港车辆需排队超10小时,“代排”每小时80元 海南春节进出岛高峰期 海南春节离岛车流高峰是哪几天