全局数据共享MobX
Mobx
全局数据共享(又叫做:状态管理)是为了解决组件之间数据共享的问题。
在小程序中,可使用 mobx-miniprogram
配合 mobx-miniprogram-bindings
实现全局数据共享。其中:
mobx-miniprogram
用来创建 Store 实例对象mobx-miniprogram-bindings
用来把 Store 中的共享数据或方法,绑定到组件或页面中使用
1、安装 mobx-miniprogram
和 mobx-miniprogram-bindings
npm install --save mobx-miniprogram mobx-miniprogram-bindings
注意
:MobX 相关的包安装完毕之后,记得重新构建 npm
2、创建 MobX Store
在跟目录下新建store
文件夹,并创建store.js
文件
// 创建 Store 的实例对象
import {action, observable} from '../miniprogram/miniprogram_npm/mobx-miniprogram/index.js'
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
})
})
在页面上使用 Store
1、将 Store 中的成员绑定到页面中
import { createStoreBindings } from '../../miniprogram/miniprogram_npm/mobx-miniprogram-bindings/index'
import { store } from '../../store/store'
Page({
onLoad() {
// 绑定 MobX store
this.storeBindings = createStoreBindings(this, {
store, // 需要绑定的数据仓库
fields: ['numA','numB','sum'], // 将哪些数据绑定到当前页面进行使用
actions: ['updateNum1'], // 将哪些方法绑定到当前页面使用
})
},
onUnload() {
// 解绑
this.storeBindings.destroyStoreBindings()
},
btnHandler1(e){
this.updateNum1(e.target.dataset.step)
}
})
2、在页面上使用 Store 中的成员
<view>{{numA}}+{{numB}}={{sum}}</view>
<van-button type="primary" bindtap="btnHandler1" data-step="{{1}}">
numA+1
</van-button>
---
<van-button type="danger" bindtap="btnHandler1" data-step="{{-1}}">
numA-1
</van-button>
在组件中使用 Store
1、将 Store 中的成员绑定到组件中
// components/test/test.js
import {storeBindingsBehavior} from '../../miniprogram/miniprogram_npm/mobx-miniprogram-bindings/index'
import {store} from '../../store/store'
Component({
behaviors:[storeBindingsBehavior],
storeBindings:{
store,
fields:{
numA:()=>store.numA, // 方法一
numB:(store)=>store.numB, // 方法二
sum:'sum' // 方法三
},
actions:{
updateNum2:'updateNum2'
}
},
/**
* 组件的方法列表
*/
methods: {
btnHandler2(e){
this.updateNum2(e.target.dataset.step)
}
}
})
2、在组件中使用 Store 中的成员
<view>{{numA}}+{{numB}}={{sum}}</view>
<van-button type="primary" bindtap="btnHandler2" data-step="{{1}}">
numB+1
</van-button>
---
<van-button type="danger" bindtap="btnHandler2" data-step="{{-1}}">
numB-1
</van-button>
详细信息可查看:官方文档