微信小程序全局数据共享

1.概念

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

2.小程序中共享方案

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

3.Mobx相关的包


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

4.将store中的成员绑定到页面中

4.1创建store.js

// 创建store实例对象
// 引入observable是定义store的包,action是定义修改store数据的包
import {
  observable,
  action
} from "mobx-miniprogram"
// 通过observalbe方法就可以创建store
export const store = observable({
  // 数据字段-共享的数据
  numA: 1,
  numB: 2,
  // 计算属性 get代表就是只读的
  get sum() {
    return this.numA + this.numB
  },
  // action方法,用来修改store中的数据(外界数据是不能更改的)
  // action方法包裹方法才行
  updateNum1: action(function (step) {
    this.numA += step
  }),
  updateNum2: action(function (step) {
    this.numB += step
  })
})

4.2.页面js文件

// 这个函数用于将 MobX store 绑定到小程序的页面
import {createStoreBindings} from "mobx-miniprogram-bindings"
// 引入store
import {store} from "../../store/store"
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // this指的是当前页面,当函数执行完成后,有一个返回值,挂在在页面上,作为属性
    // {包含是三个属性}
    // store数据源,fields需要的字段或者属性,绑定在页面上,actions保存需要的方法
  this.storeBindings= createStoreBindings(this,{store,
    fields:['numA','numB','sum'],
    actions:['updateNum1']
    })
  },

4.3contact.wxml文件

<!--pages/contact/contact.wxml-->
<view>{
   
   {numA}}+{
   
   {numB}}={
   
   {sum}}</view>
<van-button type="primary" bindtap="btnHandler" data-step="{
   
   {1}}">numA+1</van-button>
<van-button type="danger" bindtap="btnHandler" data-step="{
   
   {-1}}">numA-1</van-button>

4.4contact.js文件

  btnHandler(e){
    this.updateNum1(e.target.dataset.step)
  },

4.5页面展示

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

5.1组件的js

import {storeBindingsBehavior} from "mobx-miniprogram-bindings"
import {store} from "../../store/store"
 behaviors:[storeBindingsBehavior],
  storeBindings:{
   //数据源
   store,
   fields:{
     //映射关系
     numA:"numA",
     numB:"numB",
     sum:"sum"
   },
   actions:{
     updateNum2:"updateNum2"
  }
  },

5.2组件的wxml文件

<view>{
   
   {numA}}+{
   
   {numB}}={
   
   {sum}}</view>
<van-button type="primary" bindtap="btnHandler2" data-step="{
   
   {1}}">numA+1</van-button>
<van-button type="danger" bindtap="btnHandler2" data-step="{
   
   {-1}}">numA-1</van-button>

5.3 组件js文件

  methods: {
    btnHandler2(e){
      this.updateNum2(e.target.dataset.step)
    }
  }

5.4页面展示

 

猜你喜欢

转载自blog.csdn.net/m0_62785037/article/details/131458173