文档:
computed | 微信开放文档
https://github.com/wechat-miniprogram/mobx-miniprogram-bindings

全局数据共享是为了解决组件之间数据共享的问题。
开发中最常用的共享方案有:VuexReduxMobx等。
image.png
在小程序中国可以使用mobx-miniprogram配合mobx-miniprogram-bindings实现全局数据共享。
mobx-miniprogram:用于创建Store实例对象的。
mobx-miniprogram-bindings:用于Store中的共享数据或方法,绑定到组件或页面中使用。

安装

1、进行安装

  1. npm install mobx-miniprogram mobx-miniprogram-bindings --save

2、进行构建npm

创建 Store

1、新建store/index.js
2、进行导出

  1. import { observable, action } from "mobx-miniprogram";
  2. export const store = observable({
  3. // 数据字段
  4. numA: 1,
  5. numB: 2,
  6. // 计算属性
  7. get sum() {
  8. return this.numA + this.numB;
  9. },
  10. // actions
  11. update: action(function (data) {
  12. console.log(data);
  13. this.numA += data
  14. this.numB += data
  15. }),
  16. });

页面使用 Store

  1. <button bind:handleTapDefaultBtn>按钮{{ sum }}</button>
  1. // pages/store-page/store-page.js
  2. import { createStoreBindings } from "mobx-miniprogram-bindings"
  3. import { store } from "../../store/index"
  4. Page({
  5. /**
  6. * 页面的初始数据
  7. */
  8. data: {},
  9. handleTapDefaultBtn() {
  10. console.log(this.data)
  11. // 调用 Store 的方法
  12. this.update(10);
  13. },
  14. /**
  15. * 生命周期函数--监听页面加载
  16. */
  17. onLoad(options) {
  18. // 挂载到 this.storeBindings 属性上
  19. // this 表示挂在到 this 实例对象上
  20. this.storeBindings = createStoreBindings(this, {
  21. store, // store 对象
  22. fields: ["numA", "numB", "sum"], // 此页面需要需要使用 store 的数据
  23. actions: ["update"], // 此页面需要需要使用 store 的方法
  24. });
  25. },
  26. /**
  27. * 生命周期函数--监听页面初次渲染完成
  28. */
  29. onReady() {},
  30. /**
  31. * 生命周期函数--监听页面显示
  32. */
  33. onShow() {},
  34. /**
  35. * 生命周期函数--监听页面隐藏
  36. */
  37. onHide() {},
  38. /**
  39. * 生命周期函数--监听页面卸载
  40. */
  41. onUnload() {
  42. // 页面卸载销毁 store
  43. this.storeBindings.destroyStoreBindings()
  44. }
  45. })

组件使用 Store

  1. // components/test3/test3.js
  2. import { storeBindingsBehavior } from "mobx-miniprogram-bindings";
  3. import { store } from "../../store/index.js";
  4. Component({
  5. /**
  6. * 组件的属性列表
  7. */
  8. properties: {},
  9. behaviors: [storeBindingsBehavior],
  10. storeBindings: {
  11. // 指定要绑定的 Store
  12. store,
  13. // 指定要绑定的数据
  14. fields: {
  15. numA: () => store.numA,
  16. numB: (store) => store.numB,
  17. sum: "sum",
  18. },
  19. // 指定要绑定的方法
  20. actions: {
  21. buttonTap: "update",
  22. },
  23. },
  24. /**
  25. * 组件的初始数据
  26. */
  27. data: {},
  28. /**
  29. * 组件的方法列表
  30. */
  31. methods: {}
  32. })