微信小程序 小程序全局数据共享(笔记)

文章目录

      • 1. 安装 mobx
      • 2. 创建 Store 实例
      • 3. 在页面中使用 Store
        • 3.1 页面挂载
        • 3.2 页面使用
      • 4. 在组件中使用 Store
        • 4.1 组件挂载
        • 4.2 组件使用

1. 安装 mobx

在小程序中可以安装 mobx 实现全局数据共享,需要 npm 下载两个包

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

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

在微信小程序中使用 npm 下载包,需要在工具中点击构建 npm,还需要在本地设置中勾选使用 npm 模块

2. 创建 Store 实例

// store/index.js
import { observable, action } from "mobx-miniprogram"

export default observable({
  // 数据
  numA: 10,
  numB: 20,
  
  // 计算属性 
  get sum(){
	return this.numA + this.numB
  },
    
  // action 方法,用来修改 store 中的数据
  setNumA: action(function (value) {
  	this.numA = value
  }),
  setNumB: action(function (value) {
  	this.numB = value
  })
})

3. 在页面中使用 Store

3.1 页面挂载

import { createStoreBindings } from "mobx-miniprogram-bindings"
import { store } from "store/index"

Page({
  // 页面加载时挂载 Store
  onLoad() {
    this.storeBindings = createStoreBindings(this, {
      store,
      fields: ["numA", "numB", "sum"],
      actions: ["setNumA", "setNumB"]
    })
  },
  // 页面卸载时卸载 Store
  onUnload() {
    this.storeBindings.destroyStoreBindings()
  }
})

3.2 页面使用


<view bindtap="btn" data-value={{100}}>{{sum}}view>
// 在逻辑中通过 this 直接获取即可
Page({
  btn(e){
    this.setNumA(e.target.dataset.value)
  }
})

4. 在组件中使用 Store

4.1 组件挂载

import { storeBindsBehavior } from "mobx-miniprogram-bindings"
import { store } from "store/index"

Component({
 behaviors: [storeBindsBehavior],
 storeBindings: {
    store,
    fields: {
      numA: "numA",
      numB: "numB",
      sum: "sum"
    },
    actions: {
      setNumA: "setNumA",
      setNumB: "setNumB"
    }
  }
})

4.2 组件使用

组件的使用和页面一样

你可能感兴趣的:(微信小程序,小程序,微信小程序)