本文整理自网络,侵删。
小程序的 MobX 绑定辅助库
小程序的 MobX 绑定辅助库。
此 behavior 依赖开发者工具的 npm 构建。具体详情可查阅 官方 npm 文档 。可配合 MobX 的小程序构建版 npm 模块 mobx-miniprogram 使用。使用方法
需要小程序基础库版本 >= 2.2.3 的环境。
也可以直接参考这个代码片段(在微信开发者工具中打开): https://developers.weixin.qq.com/s/36j8NZmC74ac 。
- 安装 mobx-miniprogram 和 mobx-miniprogram-bindings :
npm install --save mobx-miniprogram mobx-miniprogram-bindings
- 创建 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
},
// actions
update: action(function () {
const sum = this.sum
this.numA = this.numB
this.numB = sum
})
})
- 在 Component 构造器中使用:
import { storeBindingsBehavior } from 'mobx-miniprogram-bindings'
import { store } from './store'
Component({
behaviors: [storeBindingsBehavior],
data: {
someData: '...'
},
storeBindings: {
store,
fields: {
numA: () => store.numA,
numB: (store) => store.numB,
sum: 'sum'
},
actions: {
buttonTap: 'update'
},
},
methods: {
myMethod() {
this.data.sum // 来自于 MobX store 的字段
}
}
})
- 在 Page 构造器中使用:
import { createStoreBindings } from 'mobx-miniprogram-bindings'
import { store } from './store'
Page({
data: {
someData: '...'
},
onLoad() {
this.storeBindings = createStoreBindings(this, {
store,
fields: ['numA', 'numB', 'sum'],
actions: ['update'],
})
},
onUnload() {
this.storeBindings.destroyStoreBindings()
},
myMethod() {
this.data.sum // 来自于 MobX store 的字段
}
})
接口
将页面、自定义组件和 store 绑定有两种方式: behavior 绑定 和 手工绑定 。
behavior 绑定
behavior 绑定 适用于 Component 构造器。做法:使用 storeBindingsBehavior 这个 behavior 和 storeBindings 定义段。
相关阅读 >>
更多相关阅读请进入《微信小程序》频道 >>
Vue.js 设计与实现 基于Vue.js 3 深入解析Vue.js 设计细节
本书对 Vue.js 3 技术细节的分析非常可靠,对于需要深入理解 Vue.js 3 的用户会有很大的帮助。——尤雨溪,Vue.js作者