文档:
computed | 微信开放文档
https://github.com/wechat-miniprogram/mobx-miniprogram-bindings
全局数据共享是为了解决组件之间数据共享的问题。
开发中最常用的共享方案有:Vuex
、Redux
、Mobx
等。
在小程序中国可以使用mobx-miniprogram
配合mobx-miniprogram-bindings
实现全局数据共享。mobx-miniprogram
:用于创建Store
实例对象的。mobx-miniprogram-bindings
:用于Store
中的共享数据或方法,绑定到组件或页面中使用。
安装
1、进行安装
npm install mobx-miniprogram mobx-miniprogram-bindings --save
2、进行构建npm
包
创建 Store
1、新建store/index.js
2、进行导出
import { observable, action } from "mobx-miniprogram";
export const store = observable({
// 数据字段
numA: 1,
numB: 2,
// 计算属性
get sum() {
return this.numA + this.numB;
},
// actions
update: action(function (data) {
console.log(data);
this.numA += data
this.numB += data
}),
});
页面使用 Store
<button bind:handleTapDefaultBtn>按钮{{ sum }}</button>
// pages/store-page/store-page.js
import { createStoreBindings } from "mobx-miniprogram-bindings"
import { store } from "../../store/index"
Page({
/**
* 页面的初始数据
*/
data: {},
handleTapDefaultBtn() {
console.log(this.data)
// 调用 Store 的方法
this.update(10);
},
/**
* 生命周期函数--监听页面加载
*/
onLoad(options) {
// 挂载到 this.storeBindings 属性上
// this 表示挂在到 this 实例对象上
this.storeBindings = createStoreBindings(this, {
store, // store 对象
fields: ["numA", "numB", "sum"], // 此页面需要需要使用 store 的数据
actions: ["update"], // 此页面需要需要使用 store 的方法
});
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady() {},
/**
* 生命周期函数--监听页面显示
*/
onShow() {},
/**
* 生命周期函数--监听页面隐藏
*/
onHide() {},
/**
* 生命周期函数--监听页面卸载
*/
onUnload() {
// 页面卸载销毁 store
this.storeBindings.destroyStoreBindings()
}
})
组件使用 Store
// components/test3/test3.js
import { storeBindingsBehavior } from "mobx-miniprogram-bindings";
import { store } from "../../store/index.js";
Component({
/**
* 组件的属性列表
*/
properties: {},
behaviors: [storeBindingsBehavior],
storeBindings: {
// 指定要绑定的 Store
store,
// 指定要绑定的数据
fields: {
numA: () => store.numA,
numB: (store) => store.numB,
sum: "sum",
},
// 指定要绑定的方法
actions: {
buttonTap: "update",
},
},
/**
* 组件的初始数据
*/
data: {},
/**
* 组件的方法列表
*/
methods: {}
})