1.什么是全局數據共享
全局數據共享(又叫做:狀態管理)是為了解決組件之間數據共享的問題。開發中常用的全局數據共享方案有:Vuex、Redux、MobX等。
2.小程序中的全局數據共享方案
在小程序中微信小程序組件傳值,可使用 mobx- 配合 mobx-- 實現全局數據共享。其中:mobx- 用來 創建 Store 實例對象
mobx-- 用來把 Store 中的共享數據或方法,綁定到組件或頁面中使用
全局數據共享–MobX 1.安裝MobX相關的包
在項目中運行如下的命令微信小程序組件傳值,安裝MobX相關的包:
npm install --save mobx-miniprogram@4.13.2 mobx-miniprogram-bindings@1.2.1
注意:MobX相關的包安裝完畢之后,記得刪除 目錄后,重新構建npm。
2.創建MobX的Store 實例
//在這個 JS 文件中專門來創建 Store 的實例對象
import { observable,action } from 'mobx-miniprogram'
export const store = observable({
//數據字段
numA: 1,
numB: 2,
//計算屬性
get sum(){

return this.numA + this.numB
},
//actions 函數,專門來修改 store 中數據的值
updateNum1: action(function(step) {
this.numA += step
}),
updateNum2: action(function(step) {
this.numB += step
})
})
3.將Store中的成員綁定到頁面中
import { createStoreBindings } from 'mobx-miniprogram-bindings'
import { store } from '../../store/store'
Page({
onLoad(options) {
this.storeBindings = createStoreBindings(this,{
store,
fields: ['numA','numB','sum'],
actions: ['updateNum1']
})
},

onUnload() {
this.storeBindings.destroyStoreBindings()
}
})
4.在頁面上使用Store中的成員
頁面的 wxml 結構:
<view>{{numA}} + {{numB}} = {{sum}}view>
<van-button type="primary" bindtap="btnHandler2" data-step="{{1}}">numB + 1van-button>
<van-button type="danger" bindtap="btnHandler2" data-step="{{-1}}">numB - 1van-button>

按鈕事件的處理函數
/**
* 組件的方法列表
*/
methods: {
btnHandler2(e) {
this.updateNum2(e.target.dataset.step)
}
}