微信小程序 全局数据共享 Mobx

1、首先安装MOBX

在项目所在目录下,右键选择【在外部终端窗口中打开】,运行:

npm install  --save  mobx-miniprogram@4.13.2  mobx-miniprogram-bindings@1.2.1

成功之后,在微信开发者工具中点击【工具】-【构架npm】,到此安装工作完成。

2、将需要共享的数据放在一个store.js文件中,导入mobx-miniprogram,需要共享的数据有字段num1,num2,方法sum(),updateNum1,updateNum2,注意:需要更改共享数据的方法使用:action修饰

import {
  observable,
  action
} from 'mobx-miniprogram'
export const store = observable({
  num1: 1,
  num2: 2,
  get sum() {
    return this.num1 + this.num2
  },
  updateNum1: action(function (step) {
    this.num1 = this.num1 + step
  }),
  updateNum2: action(function (step) {
    this.num2 = this.num2 + step
  })
})

3、在页面中引用store

首先导入mobx-miniprogram-bindings

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

在onLoad生命周期函数中

### 微信小程序MobX 状态管理的应用场景 #### 使用 MobX 实现全局状态共享 在微信小程序开发过程中,MobX 提供了一种简洁有效的方式来处理复杂的状态管理需求。通过 `mobx-miniprogram` 和 `mobx-miniprogram-bindings` 的组合使用,可以轻松实现跨页面和组件的数据共享[^3]。 ```javascript // store.js 创建 Store 实例对象 import { observable, action } from 'mobx-miniprogram' const counterStore = observable({ count: 0, increment: action(function() { this.count += 1; }), decrement: action(function() { this.count -= 1; }) }); export default counterStore; ``` ```html <!-- index.wxml --> <view> <text>Count: {{count}}</text> <button bindtap="increment">Increment</button> <button bindtap="decrement">Decrement</button> </view> <script> Page({ onLoad () { const CounterStore = require('../../store').default; // 绑定 Store 中的数据到当前页面 this.storeBindings = [ mobxMiniprogram.bindSync(CounterStore, ['count'], this), mobxMiniprogram.bindAction('increment', CounterStore.increment, this), mobxMiniprogram.bindAction('decrement', CounterStore.decrement, this) ]; }, onUnload () { // 页面卸载时解除绑定 this.storeBindings.forEach(binding => binding()); } }); </script> ``` 此示例展示了如何利用 MobX 来维护一个简单的计数器应用,在不同页面之间同步更新数值变化。每当点击按钮触发相应操作时,不仅会改变存储中的值,还会自动刷新视图显示最新的计数值。 #### 处理异步请求并保持 UI 同步 对于涉及网络通信或其他耗时任务的情况,可以通过集成 `miniprogram-api-promise` 将原生API转换成Promise形式来简化逻辑控制流;同时借助 MobX 对这些异步流程进行跟踪,确保界面始终反映最新状态[^5]。 ```javascript // service.js 发起 HTTP 请求的服务层封装 async function fetchData(url) { try { let response = await wx.request({ url }); return response.data; } catch (error) { console.error(error); } } ``` ```javascript // store.js 更新后的 Store 添加加载标志位以及获取远程数据的方法 import { observable, action } from 'mobx-miniprogram'; import * as Service from './service'; const appState = observable({ loading: false, items: [], fetchItems: action(async function() { this.loading = true; // 开始加载前设置标记 const data = await Service.fetchData('/api/items'); this.items = data || []; this.loading = false; // 加载完成后清除标记 }) }); export default appState; ``` 上述代码片段说明了当执行 `fetchItems()` 方法时,应用程序会在后台发起一次HTTP GET请求,并在此期间展示进度指示符给用户知道正在等待响应结果返回。一旦收到服务器回复,则立即将其解析后赋值给 `items` 属性以便立即渲染列表项。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

永远都是小白的小刘

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值