1.什么是全局数据共享
全局数据共享(又叫:状态管理)是为了解决组件之间数据共享的问题。开发中常用的全局数据共享方案有:Vuex、Redux、Mobx等
2.小程序中的全局数据共享方案
可使用mobx-miniprogram配合mobx-miniprogram-bindings实现全局数据共享。其中
- modx-miniprogram用来创建Store实例对象
- mobx-miniprogram-bindings用来把Store中的共享数据或方法,绑定到组件或页面中使用
3.安装Mobx包
注意:Mobx相关的包安装后,记得删除miniprogram-npm目录后,重新构建npm
4.创建Mobx的Store实例
//在这个js文件中,专门用来创建Store的实例对象
import {observable} from 'mobx-miniprogram'
export const store = observable({
//数据字段
numA:1,
numB:2,
//计算属性
get sum(){
return this.numA+this.numB
},
//actions方法,用来修改store中的数据
updataNum1:action(function (step)
{ this.numA += step
}),
updataNum2:action(function (step)
{ this.numB += step
}),
})
5.将store中的成员绑定到页面中
//页面js
import { createStoreBindings } from 'mobx-miniprogram-bindings'
import { store } from '../../store/store'
onLoad: function (options) {
this.storeBindings = createStoreBindings(this,{
store,//数据源
fields:['numA','numB','sum'],
actions:['updateNum1']
})
},
onUnload: function () {
//卸载这个store
this.storeBindings.destroyStoreBindings()
},
//页面wxml
<view>
{{numA}}+{{numB}} = {{sum}}
</view>
<vant-button type="danger" bindtap="btnHandler1" data-step='{{1}}'>numA+1</vant-button>
<vant-button type="primary" bindtap="btnHandler1" data-step='{{-1}}'>numA-1</vant-button>
//页面js
btnHandler1(e){
// console.log(e)
this.updateNum1(e.target.dataset.step)
},
6.将store成员绑定到组件中
import { storeBindingsBehavior } from 'mobx-miniprogram-bindings'
import { store } from '../../store/store'
Component({
/**
* 组件的属性列表
*/
behaviors:[storeBindingsBehavior],//通过storeBindingsBehavior实现自动绑定
//不知道storeBindings是从哪冒出来的
storeBindings:{
store,
fields:{//fields不能写错,写错会无法渲染
numA:()=>store.numA,//绑定的第一种方式
numB:(store)=>store.numB,//绑定的第2种方式
sum:'sum'//绑定的第3种方式
},
actions:{
updateNum2:'updateNum2'
}
},
})
在组件中使用Store中的成员
//组价.wxml结构
<view>
{{numA}}+{{numB}}={{sum}}
</view>
<vant-button type="danger" bindtap="btnHandler2" data-step='{{1}}'>numB+1</vant-button>
<vant-button type="primary" bindtap="btnHandler2" data-step='{{-1}}'>numB-1</vant-button>
//组件的方法列表
methods: {
btnHandler2(e){
this.updateNum2(e.target.dataset.step)
}
}