文件來源:https://developers.weixin.qq.com/community/develop/article/doc/0004686e3c8980b53469f176e51413
在小程序中引入 MobX
在小程序項目中,可以通過 npm 的方式引入 MobX 。
npm init -y
引入 MobX :
npm install --save mobx-miniprogram mobx-miniprogram-bindings
(這里用到了 mobx-miniprogram-bindings 模塊,模塊說明在這里: https://developers.weixin.qq.com/miniprogram/dev/extended/functional/mobx.html 。)
npm 命令執行完后,記得在開發者工具的項目中點一下菜單欄中的 工具
- 構建 npm
。
建立數據倉庫
數據倉庫通常專門寫在store的 js 文件中。
import { observable, action } from 'mobx-miniprogram' // 數據倉庫 export const store = observable({ list: [], // 天氣數據(包含列表和詳情) // 設置天氣列表,從網絡上獲取到數據之后調用 setList: action(function (list) { this.list = list }), })
在首頁中使用數據倉庫
如果需要在頁面中使用數據倉庫里的數據,需要調用 createStoreBindings
來將倉庫中的數據綁定到頁面數據中,然后就可以在頁面中直接使用倉庫數據了。
import { createStoreBindings } from 'mobx-miniprogram-bindings' import { store } from './store' Page({ onLoad() { // 綁定 MobX store this.storeBindings = createStoreBindings(this, { store, // 需要綁定的數據倉庫 fields: ['list'], // 將 this.data.list 綁定為倉庫中的 list ,即天氣數據 actions: ['setList'], // 將 this.setList 綁定為倉庫中的 setList action }) // 從服務器端讀取數據 wx.showLoading() wx.request({ // 請求網絡數據 // ... success: (data) => { wx.hideLoading() // 調用 setList action ,將數據寫入 store this.setList(data) } }) }, onUnload() { // 解綁 this.storeBindings.destroyStoreBindings() }, })
這樣,可以在 wxml 中直接使用 list :
<view class="item" wx:for="{{list}}" wx:key="date" data-index="{{index}}"> <!-- 這里可以使用 list 中的數據了! --> <view class="title">{{item.date}} {{item.summary}}</view> <view class="abstract">{{item.temperature}}</view> </view>
在詳情頁中使用數據倉庫
在詳情頁中,同樣可以使用 createStoreBindings
來將倉庫中的數據綁定到頁面數據中:
import { createStoreBindings } from 'mobx-miniprogram-bindings' import { store } from './store' Page({ onLoad(args) { // 綁定 MobX store this.storeBindings = createStoreBindings(this, { store, // 需要綁定的數據倉庫 fields: ['list'], // 將 this.data.list 綁定為倉庫中的 list ,即天氣數據 }) // 頁面參數 `index` 表示要展示哪一條天氣詳情數據,將它用 setData 設置到界面上 this.setData({ index: args.index }) }, onUnload() { // 解綁 this.storeBindings.destroyStoreBindings() }, })
<view class="title">{{list[index].date}}</view> <view class="content">溫度 {{list[index].temperature}}</view> <view class="content">天氣 {{list[index].weather}}</view> <view class="content">空氣質量 {{list[index].airQuality}}</view> <view class="content">{{list[index].details}}</view>
完整示例
完整例子可以在這個代碼片段中體驗: https://developers.weixin.qq.com/s/YhfvpxmN7HcV