微信小程序-全局数据共享MobX
1.开发中常用的数据共享方案
为了解决组件之间的数据共享,开发中常用的数据共享方案有:Vuex/Redux/MobX等
2.小程序中全局数据共享方案-MobX
在小程序中,可使用mobx-miniprogram配合mobx-miniprogram-bindings实现全局数据共享。
- mobx-miniprogram用来创建Store实例对象
- mobx-miniprogram-bindings用来把共享的数据或方法,绑定到组件或页面中使用。
3.安装及使用
3.1安装
命令如下:
npm install --save mobx-miniprogram@版本 mobx-miniprogram-bindings@版本
注意:重新构建npm
3.2 全局数据共享实例
在根目录下创建store/store.js,专门用来创建Store实例
// 在这个 JS 文件中,专门来创建 Store 的实例对象
//按需引入,observable专门用来创建store对象
import { observable, action } from 'mobx-miniprogram'
export const store = observable({
//共享数据 的 数据字段
numA: 1,
numB: 2,
// 计算属性,get表示只读,只能获取,无法重新赋值
get sum() {
return this.numA + this.numB
},
// actions 函数,专门来修改 store 中数据的值,里面是一个函数
updateNum1: action(function (step) {
this.numA += step
}),
updateNum2: action(function (step) {
this.numB += step
})
})
3.3 绑定到页面
在页面的.js文件中,写如下代码
//导入createStoreBindings,用来把共享的数据或方法,绑定到组件或页面中使用
import { createStoreBindings } from 'mobx-miniprogram-bindings'
// 导入store
import { store } from '../../store/store'
Page({
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
//将store/fileds-数据/actions-方法 绑定给this
this.storeBindings = createStoreBindings(this, {
store,
fields: ['numA', 'numB', 'sum'],
actions: ['updateNum1']
})
},
//普通方法的定义
btnHandler1(e) {
// e.target.dataset是固有属性,保存传来的step
// 对应的wxml--<button type="primary" bindtap="btnHandler1" data-step="{{1}}">numA + 1<button> data-step属性表示
this.updateNum1(e.target.dataset.step)
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
//销毁绑定
this.storeBindings.detroyStoreBindings()
}
})
3.4 绑定到组件
3步:引入、挂载、绑定
//引入 storeBindingsBehavior
import { storeBindingsBehavior } from 'mobx-miniprogram-bindings'
//引入 store
import { store } from '../../store/store'
Component({
//将storeBindingsBehavior挂载到behaviors上
behaviors: [storeBindingsBehavior],
storeBindings: {
// 数据源
store,//指定要绑定的store
fields: {
numA: ()=>store.numA,//绑定字段的第1种方式
numB: (store)=>store.numB,//绑定字段的第2种方式
sum: 'sum'//绑定字段的第3种方式
},
//方法
actions: {
//指定要绑定的方法
updateNum2: 'updateNum2'
}
},
/**
* 组件的方法列表
*/
methods: {
btnHandler2(e) {
this.updateNum2(e.target.dataset.step)
}
}
})