全局数据共享

155 阅读1分钟

image.png

1.安装 MobX 相关的包

在项目中运行如下的命令,安装 MobX 相关的包:

npm install --save mobx-miniprogram@4.13.2 mobx-miniprogram-bindings@1.2.1

注意: MobX 相关的包安装完毕之后,记得删除 miniprogram npm 目录后,重新构建 npm

image.png

2.创建MobX的Store 实例

//引入mobx-miniprogram包中的observable方法
import { observable, action } from 'mobx-miniprogram'
//调用observable这个方法创建store实例对象
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 中的成员绑定到页面中

// 页面的 .js 文件
import { createStoreBindings } from 'mobx-miniprogram-bindings'
import { store } from '../../store/store'
Page({
   // 生命周期函数--监听页面加载
   onLoad: function () { 
      //调用createStoreBindings方法绑定在参数一this上,参数二放置一个配置项放入数据源store,
      //还有需要的字段以及方法,fields接收字段数组,actions接收方法数组,
      //再挂载在this.storeBindings这个自定义属性上
      this.storeBindings = createStoreBindings(this,{
       store,//数据源
       fields: ['numA' ,'numB' ,' sum' ], //用到的字段
       actions: ['updateNum1'] //用到的方法
     })
   },
   // 生命周期函数--监听页面卸载
   onUnload: function () {
      //页面卸载就访问自定义属性this.storeBindings调用destroyStoreBindings()进行解绑
      this.storeBindings.destroyStoreBindings()
   }
 })

image.png

5.将store 中的成员绑定到组件中

import ( storeBindingsBehavior } from 'mobx-miniprogram-bindings'
import { store ] from '../../store/store'
Component({
     // 通过 storeBindingsBehavior 来实现自动绑定
     behaviors: [storeBindingsBehavior],
     storeBindings:{
        // 指定要绑定的 Store
       store ,
       // 指定要绑定的字段数据
       fields: {
        numA: () => store.numA ,     // 绑定字段的第 1 种方式
        numB: (store) => store.numB// 绑定字段的第 2 种方式
        sum: 'sum'                   // 绑定字段的第 3种方式
        },
       actions:{ 
        updateNum2:'updateNum2' // 指定要绑定的方法
        }
     },
   })  
        

image.png