[email protected] mobx miniprogram [email protected] 注意:MobX 相关的包安装完毕之后,记得删除 miniprogram npm 目录后,重新构建 npm。 2. 创建 MobX ...">

当前位置:网站首页>小程序实现全局数据共享

小程序实现全局数据共享

2022-06-10 14:37:00 SpaceX7_s

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

npm i --save mobx-[email protected]4.13.2 mobx-miniprogram-[email protected]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)
    }
原网站

版权声明
本文为[SpaceX7_s]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_45842954/article/details/125147805