全局数据共享-MobX的使用

安装步骤:

1、npm install --save [email protected] [email protected]

2、构建npm

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

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

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

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

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

store.js 文件:


import {action, observable} 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
  })
})

在页面中的使用:

js文件

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

  /**
   * 页面的初始数据
   */
  data: {
    
  },
  btnHandler1(e) {
    this.updateNum1(e.target.dataset.step)
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.storeBindings = createStoreBindings(this, {
      store,
      fields: ['numA','numB','sum'],
      actions: ['updateNum1']
    })
  },

})

wxml文件

<view>
  {
   
   {numA}} + {
   
   {numB}} = {
   
   {sum}}
</view>
<button bindtap="btnHandler1" data-step="{
   
   {1}}">numA + 1</button>
<view>
</view>
<button bindtap="btnHandler1" data-step="{
   
   {-1}}">numA - 1</button>

在组件中的使用:

js文件:

// components/numbers/numbers.js
import {storeBindingsBehavior} from 'mobx-miniprogram-bindings'
import {store} from '../../store/store'

Component({
  behaviors: [storeBindingsBehavior],//通过storeBindingsBehavior实现自动绑定
  storeBindings: {
    store,//指定要绑定的store
    fields:{ //指定绑定的字段数据
      numA: ()=> store.numA, //绑定字段的第2种方式
      numB: (store) => store.numB, //绑定字段的第2种方式
      sum: 'sum' //绑定字段的第3种方式
    },
    actions: { //指定要绑定的方法
      updateNum2: 'updateNum2'
    }
  },
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {

  },

  /**
   * 组件的方法列表
   */
  methods: {
    btnHandler2(e) {
      this.updateNum2(e.target.dataset.step)
    },
  }
})

猜你喜欢

转载自blog.csdn.net/RreamigOfGirls/article/details/130727383