使用MobX来实现全局数据共享

引入两个包,MobX包和绑定MobX小程序绑定包

npm install --save mobx-miniprogram mobx-miniprogram-bindings
//安装两个包,mobx包,另外是小程序绑定包

创建MobX的store,此处存放我们要共享的数据,计算属性和方法

// store.js
import { observable, action } from "mobx-miniprogram";

export const store = observable({
  // 数据字段
  numA: 1,
  numB: 2,

  // 计算属性
  get sum() {
    return this.numA + this.numB;
  },

  // actions
  updateNam1:action(function(step){
    this.numA += step
  }),

  updateNam2:action(function(step){
    this.numB -= step
  })
});

在要使用共享数据页面的js代码中引入之前我们在store中存放的数据,引入creatStoreBinding,从mobx-miniprograme-binding

\\一下页面适合使用component中的js文件创建,page中也可使用这种方法创建,但是可能会出现兼容性问题。
\\因此我们推荐使用组件的方法来使用mobx
import { storeBindingsBehavior } from "mobx-miniprogram-bindings";
import { store } from "./store";

Component({
  behaviors: [storeBindingsBehavior],
  data: {
    someData: "...",
  },
  storeBindings: {
    store,
    fields: {
      //数据
      numA: () => store.numA,
      numB: (store) => store.numB,
      //计算属性
      sum: "sum",
    },
    actions: {
    //方法
      buttonTap: "update",
    },
  },
  methods: {
    myMethod() {
      this.data.sum; // 来自于 MobX store 的字段
    },
  },
});

销毁store-binding

使用component没有见到官方文档要销毁store-binding。使用page要销毁


版权声明:本文为bigdragon123456原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。