全局数据共享-微信小程序开发(二十九 )

1. 什么是全局数据共享

全局数据共享(又叫做:状态管理)是为了解决组件之间数据共享的问题。
开发中常用的全局数据共享方案有:Vuex、Redux、MobX 等。

2. 小程序中的全局数据共享方案

在小程序中,可使用 mobx-miniprogram 配合 mobx-miniprogram-bindings 实现全局数据共享。其中:
⚫ mobx-miniprogram 用来创建 Store 实例对象
⚫ mobx-miniprogram-bindings 用来把 Store 中的共享数据或方法,绑定到组件或页面中使用

全局数据共享 - MobX

1. 安装 MobX 相关的包

在项目中运行如下的命令,安装 MobX 相关的包:

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

注意: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
  },
  // action 方法,用来修改store 中的数据
  updateNumq:action(function(step){
    this.numA += step
  }),
  updateNum2:action(function(step){
    this.numB += step
  })
})

3. 将 Store 中的成员绑定到页面中

//页面的 .js文件
import { createStoreBindings} from 'mobx-miniprogram-bindings'
import { store } from '../../store/store'
Page({
   onLoad(options) { //生命周期函数--监听页面加载
    this.storeBindings = createStoreBindings(this,{
      store,
      fields:['numA','numB','sum'],
      actions:['updateNum1']
    })
  },
  onUnload() { //生命周期函数--监听页面卸载
    this.storeBindings.destroyStoreBindings()
  }
})

4. 在页面上使用 Store 中的成员

//页面的wxml结构
<view>{{numA}} + {{numB}} = {{sum}}</view>
<vant-button type="primary" bindtap="btnHandler" data-step="{{1}}">numA+1</vant-button>
<vant-button type="primary" bindtap="btnHandler" data-step="{{-1}}">numA-1</vant-button>

  //按钮 tap 事件处理函数
  btnHandler(e){
    this.updateNum1(e.target.dataset.step)
  }

5. 将 Store 中的成员绑定到组件中

//页面的 .js文件
import { createStoreBindings, storeBindingsBehavior} from 'mobx-miniprogram-bindings'
import { store } from '../../store/store'
Component({
  behaviors:[storeBindingsBehavior],//通过storeBindingsBehavior 来实现自动绑定
  storeBindings:{
    store, //指定要绑定的Store
    fields:{ //指定要绑定的字段数据
      numA:()=>store.numA,  //绑定字段的第1中方式
      numB:(store)=>store.numB, //绑定字段的第2种方式
      sum:'sum'   //绑定字段的第3种方式
    },
    actions:{ //指定要绑定的方法
      updateNum2:'updateNum2'
    }
  }
})

6. 在组件中使用 Store 中的成员

//组件的wxml结构
<view>{{numA}} + {{numB}} = {{sum}}</view>
<vant-button type="primary" bindtap="btnHandler" data-step="{{1}}">numA+1</vant-button>
<vant-button type="primary" bindtap="btnHandler" data-step="{{-1}}">numA-1</vant-button>

  //组件的按钮 tap 事件处理函数
  btnHandler(e){
    this.updateNum2(e.target.dataset.step)
  }
posted @ 2022-08-13 17:13  清和时光  阅读(242)  评论(0编辑  收藏  举报