微信小程序全局数据共享方案:mobx-miniprogram

1、执行命令

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

2、重新安装npm

3、创建store.js

        地址举例:/store/store.js

import {
  observable,
  action
} from 'mobx-miniprogram'
export const store = observable({
  // 设置共享数据
  num1: 1,
  num2: 2,

  // getters 计算属性
  get sum() {
    return this.num1 + this.num2
  },

  // action 操作数据的方法
  updateNum1: action(function (num) {
    this.num1 += num
  }),
  updateNum2: action(function (num) {
    this.num2 += num
  })
})

4、在Pages页面中引入

import {createStoreBindings} from'mobx-miniprogram-bindings'
import {store} from '../../store/store'

Page({
  // ...

  // 页面加载
  onLoad: function (options) {
    // 手工绑定 
    this.storeBindings = createStoreBindings(this, {
      store,
      fields: ['num1', 'num2', 'sum'],
      actions: ['updateNum1', 'updateNum2']
    })
  },

  // 通过事件处理函数 调用store 中的方法
  num1Handel(){
    this.updateNum1(1)
  },
  num2Handel(){
    this.updateNum2(-1)
  },

  // 页面初次渲染完成
  onReady: function () {
    // 测试是否获取成功
    console.log(this.data.num1);
  },

  // 页面卸载
  onUnload: function () {
    // 一定要调用清理函数,否则将导致内存泄漏!
    this.storeBindings.destroyStoreBindings()
  },
})

5、在组件Component中引用

import {
  storeBindingsBehavior
} from "mobx-miniprogram-bindings"
import {
  store
} from '../../store/store'
Component({
  // behavior 绑定
  behaviors: [storeBindingsBehavior],
  storeBindings: {
    store,
    fields: {
      num1: () => store.num1,
      num2: storeBe => storeBe.num2,
      sum: 'sum'
    },
    actions: {
      updateNum1: 'updateNum1',
      updateNum2: 'updateNum2',
    }
  },

  // 使用store 方法
  methods: {
    num1Handel(){
      this.updateNum1(1)
    },
    num2Handel(){
      this.updateNum2(-1)
    }
  }
})

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值