微信小程序 Mobx实现数据共享

2023-06-13  本文已影响0人  一只小vivi

1. 定义:全局数据共享(又叫做:状态管理)是为了解决组件之间数据共享的问题。开发中常用的全局数据共享方案有:Vuex、Redux、MobX 等。而我们微信小程序常用的全局共享方案是:MobX

image.png

我们可以通过上面这张图清除的看到,如果不使用MobX全局数据共享的话,如果需要调用某个组件,则需要一层一层调用,如果定义了全局数据共享,那么可以直接拿到数据,不需要一层一层调用

2. 全局数据共享的具体方案

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

3. 使用

4.创建store.js

1.在根目录中创建store文件夹,文件夹下创建store.js文件
2.store.js文件中引入mobx-miniprogram中的 observable、action

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

export const store = observable({
  // 字段/数据
count1: 1,
count2: 2,
// 计算属性:用get定义,(只读不能修改)
    get count_sum() {
        return this.count1 + this.count2
    },
  // action方法:用来修改store中的值
  updateCount1: action(function (step) {
      this.count1 += step
  })
})

页面中:使用store(Page页面中)

1.使用store数据的页面( .js 文件中):
import { createStoreBindings } from "mobx-miniprogram-bindings"
import { store } from '../../store/store.js'
 
Page({
 // 点击事件
    addCount(e) {
        // 获取传入值: e.target.dataset 
        this.updateCount1(e.target.dataset.addstep)
    },
    onLoad: function () {
        this.storeBindings = createStoreBindings(this, {
            store, // 数据源(将store中的某些字段、方法绑定到当前页面中)
            fields: ['count1'], // 将哪些字段绑定到此页面中进行使用
            actions: ['updateCount1'] // 将哪些方法绑定到此页面中
        })
    },
    onUnload: function () {
        this.storeBindings.destroyStoreBingds()
    },
})

2.使用store数据的页面( .wxml 文件中):(操作效果:点击页面中’store_count +1‘按钮,store_count会与store_count_sum的值一起增加)
<!-- 获取 store 中共享数据 -->
<view>{{count1}} + {{count2}} = {{count_sum}}</view>
<!-- 绑定addCount方法,传入+=Num。
     方法中:
            1.在e.target.dataset中获取传入的数据。
            2. 执行storeBindings变量 action中的 updateCount1方法,让store中的count1 +2  
-->
<button bindtap="addCount" data-addStep='{{2}}'>count1 +1</button>

组件中:使用store(Component组件中)

1.使用store数据的页面( .js 文件中):
import { storeBindingsBehavior } from "mobx-miniprogram-bindings"
import { store } from '../../store/store'
Component({
    behaviors:[storeBindingsBehavior], // 通过 storeBindingsBehavior 来实现自动绑定

    storeBindings:{  
        store,// 指定要绑定的 store
        fields:{ // 指定要绑定的字段数据
            count1:()=>store.count1, // 第一种写法(了解即可)
            count2:(store)=>store.count2, // 第二种写法(了解即可)
            count_sum:'count_sum' // 第三种写法(推荐精简)
        },
        actions:{ // 指定要绑定的方法
            getSum:'updateCount1'// 结构:自己定义的名(随便起,合法就行) : store 中的方法
        }
    },
    methods: {
       addCount(){
            this.getSum(8)//调用store中的方法。调用名称为当前页面重新定义的名称
        }
    }
})
2.使用store数据的页面( .wxml 文件中)
<view>{{count1}} + {{count2}} = {{count_sum}}  </view>
<van-button bindtap="addCount" >add +8 </van-button>
上一篇 下一篇

猜你喜欢

热点阅读