1. 什么是全局数据共享
全局数据共享(状态管理),是为了解决组件之间数据共享的问题。 开发中常用的全局数据共享方案有:Vuex,Redux,MobX等。
2. 小程序中的全局数据共享方案
在小程序中,可以使用mobx-minirogram配合mobx-miniprogram-bindings实现全局数据共享, mobx-miniprogram用来创建Store实例对象 mobx-miniprogram-bindings用来把Store中的共享数据或方法,绑定到组件或页面中使用
3. 小程序中使用MobX
3.1 安装MobX相关的包
npm install --save mobx-miniprogram mobx-miniprogram-bingings
3.2 创建Store实例对象
新建Store文件夹->store.js文件
//store.js
import {observable,action} from 'mobx-miniprogram'
export const store = observable({
// 数据字段
numA:1,
numB:2,
//计算属性
get sum(){
return this.numA + this.numB
},
//action 用来修改数据
updateNumA:action(function(step){
this.numA += step
}),
updateNumB:action(step=>{
this.numB+=step
})
})
3.3 将Store中的成员绑定到页面中
import {createStoreBindings} from 'mobx-miniprogram-bindings'
import {store} from '../../store/store'
Page({
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
this.storeBindings = createStoreBindings(this,{
store,
fields:['numA','numB','sum'],
actions:['updateNumA','updateNumB']
})
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
this.storeBindings.destroyStoreBindings()
},
})
3.4 页面使用
//.wxml
<view>{{numA}}+{{numB}}={{sum}}</view>
<van-button type="primary" bindtap="addNumA" data-step="{{1}}">numA++</van-button>
<van-button type="primary" bindtap="reduceNumA" data-step="{{-1}}">numA--</van-button>
//.js
addNumA(e){
this.updateNumA(e.target.dataset.step)
},
reduceNumA(e){
this.updateNumA(e.target.dataset.step)
},
3.5 组件的使用
//wxml
<view>{{numA}}+{{numB}}={{sum}}</view>
<van-button type="primary" bindtap="addNumB" data-step="{{1}}">numB++</van-button>
<van-button type="primary" bindtap="addNumB" data-step="{{-1}}">numB--</van-button>
//js
// components/number/number.js
import {storeBindingsBehavior} from 'mobx-miniprogram-bindings'
import {store} from '../../store/store'
Component({
behaviors:[storeBindingsBehavior],
storeBindings:{
store,
fields:{
numA:()=>store.numA,
numB:'numB',
sum:'sum'
},
actions:{
updateNumB:'updateNumB'
}
},
methods: {
addNumB(e){
console.log();
console.log(e.target.dataset.step);
this.updateNumB(e.target.dataset.step)
}
}
})