【微信小程序】全局数据共享

1.什么是全局事件共享

全局数据共享(又叫做:状态管理)是为了解决组件之间数据共享的问题。

开发中常用的全局数据共享方案有:VueX、ReduX、MobX等。

image

2.小程序中的全局数据共享方案

在小程序中,可使用mobx-miniprogram配合mobx-miniprogram-bindings实现全局数据共享。其中:

  • mobx-miniprogram用来创建Store实例对象
  • mobx-miniprogram-bindings 用来把Store 中的共享数据或方法,绑定到组件或页面中使用

image

1.安装mobx相关的包

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

npm install --save mobx-miniprogram
npm install --save mobx-miniprogram-bindings

2.创建mobx的store实例

//  在这个js中,专门创建store的实例对象
import { observable,action} from 'mobx-miniprogram'
export const store= observable({
    numberA:1,
    numberB:2,
    // 计算属性
    get sum(){
       return this.numberA+this.numberB
    },
    // actions方法,用来修改store中的数据
    updatenumberA:action(function (step) {
        this.numberA=step
    }),
    updatenumberB:action(function (step) {
        this.numberB=step
    })
})

image

3.将Store中的成员绑定到页面中

// 导入store所需的模块
import {createStoreBindings} from 'mobx-miniprogram-bindings'
import Store from '../../store/store'
  onLoad: function (options) {
        this.storeBindings=createStoreBindings(this,{
            store,
            fields:['numberA','numberB','sum'],
            actions:['updatenumberA']
        })
    },
    onUnload: function () {
        this.storeBindings.destroyStroeBindings()
    },
//、、、、、、、、、、、、、、、、、、、、、
<van-button type="danger" bindtap="addNumberA">危险</van-button>
numberA:{{numberA}}
numberB:{{numberB}}
num:{{sum}}
// 、、、、、、、、、、、、、、、、、、、、、、、
 addNumberA(){
        this.updatenumberA(10)
    },

image


4.将Store中的成员绑定到组件中

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 的字段
    },
  },
});

image

5.在组件中 使用store中的成员

image

posted @ 2022-06-03 00:29  一个大不刘blog  阅读(481)  评论(0编辑  收藏  举报