小程序实现全局数据共享

本文介绍了如何在微信小程序中利用MobX进行数据管理,包括安装配置、Store实例创建、页面中绑定和组件间通信。通过 MobX 的 observable、action 和 bindings,实现实时状态管理和组件间数据同步。
摘要由CSDN通过智能技术生成

1安装数据共享第三方包 Mobx

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

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

2. 创建 MobX 的 Store 实例

在根目录下创建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方法,用来修改store中的数据
  updateNum1:action(function(step){
    this.numA += step
  }),
  updateNum2:action(function(step){
    this.numB += step
  })
})
4.在页面中使用store
//首先引入方法
import { createStoreBindings } from "mobx-miniprogram-bindings";
import {store} from '../../store/store'

 /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  this.storeBindings=  createStoreBindings(this,{
      //数据源
      store,
      //映射变量和计算属性
      fields:['numA','numB','sum'],
      //映射方法
      actions:['updateNum1']
    })
  },
   /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
      this.storeBindings.destroyStoreBindings()
  },

在页面中使用store的数据

<view>{{numA}}+{{numB}}={{sum}}</view>
<button type="primary" bindtap="btnclick" data-step="{{1}}">numA+1</button>
<button type="primary" bindtap="btnclick" data-step="{{-1}}">numA-1</button>
//在js中调用方法
 btnclick(e){
     this.updateNum1(e.target.dataset.step)
  },
在组件中使用store
import { storeBindingsBehavior } from "mobx-miniprogram-bindings";
import { store } from "../../store/store";
 //通过storeBindingsBehavior来实现自动绑定
  behaviors: [storeBindingsBehavior],
  /**
   * 组件的属性列表,接收页面传过来的参数
   */
  storeBindings: {
    
    store,//指定要绑定的store
    fields:{

      numA:'numA',
      numB:'numB',
      sum:'sum'
    },
    actions: {//指定要绑定的方法
      updateNum2: 'updateNum2'
    }
  },

页面中使用


<view>{{numA}}+{{numB}}={{sum}}</view>
<button type="primary" bindtap="btnclick" data-step="{{1}}">numA+1</button>
<button type="primary" bindtap="btnclick" data-step="{{-1}}">numA-1</button>
//在methods中调用方法
 btnclick(e){
      
      this.updateNum2(e.target.dataset.step)
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值