1. Concept
Global data sharing (also called: state management) is to solve the problem of data sharing between components.
2. Sharing scheme in the mini program
In small programs, you can use mobx-miniprogram with mobx-miniprogram-bindings to realize global data sharing. mobx-miniprogram is used to create Store instance objects. mobx-miniprogram-bindings is used to bind
shared data or methods in Store to components or used in the page
3. Mobx related packages
npm install --save [email protected] [email protected]
4. Bind the members in the store to the page
4.1 Create 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. Page js file
// 这个函数用于将 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 file
<!--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 file
btnHandler(e){
this.updateNum1(e.target.dataset.step)
},
4.5 Page display
5. Bind the members in the store to the component
5.1 component 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 The wxml file of the component
<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 Component js file
methods: {
btnHandler2(e){
this.updateNum2(e.target.dataset.step)
}
}
5.4 Page display