当前位置: 首页 > 工具软件 > MobX > 使用案例 >

Mobx

马嘉勋
2023-12-01

Mobx


在小程序中通过Mobx实现全局数据共享

可以使用 mobx-miniprogram配合mobx-miniprogram-bindings实现全局数据共享

mobx-miniprogram用来创建Store实例对象

mobx-miniprogram-bindings用来把Store中的共享数据或方法,绑定到组件或页面中使用

安装Mobx相关依赖

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



创建Mobx的Store实例

import { observable, action } from 'mobx-miniprogram'

export const store = observable({
  // 数据字段
  numA: 1,
  numB: 2,
  // 计算属性
  getSum() {
    return this.numA + this.numB
  },
  // actions方法,用来修改store中的数据
  updateNum1:action(function(step){
    this.numA += step
  }),
  updateNum2:action(function(step){
    this.numB += step
  }),
})



页面中使用Mobx


Store中的成员绑定到页面上

// 页面的 .js 文件
import { createStoreBindings } from 'mobx-miniprogram-bindings'
import { store } from '../../store/store'

Page({
  onLoad: function () {		// 生命周期函数--监听页面加载
    this.storeBindings = createStoreBindings(this, {
      store,				// 数据源
      fields: ['numA', 'numB', 'sum'],	// 需要从数据源中取出的数据
      actions: ['updateNum1']			// 需要从数据源中映射的方法
    })
  },
  onUnload: function () {	// 生命周期函数--监听页面卸载
    this.storeBindings.destroyStoreBindings()
  }
})

在页面结构中可以直接使用变量和映射的方法



组件中使用Mobx


Store中的成员绑定到组件上

// 组件的 .js 文件
import { storeBindingsBehavior } from 'mobx-miniprogram-bindings'
import { store } from '../../store/store'

Component({
  behaviors: [storeBindingsBehavior],		// 通过 storeBindingsBehavior 来实现自动绑定
  storeBindings: {
    store,		// 指定需要绑定的 Store
    fields: {	// 指定需要绑定过的字段数据
      numA: () => store.numA,		// 绑定字段的第一种方式
      numB: (store) => store.numA,	// 绑定字段的第二种方式
      sum: 'sum'					// 绑定字段的第三种方式
    },
    actions: {						// 指定要绑定的方法
      updateNum2: 'updateNum2'
    }
  }
})

在组件结构中可以直接使用变量和映射的方法

 类似资料: