小程序中的全局数据共享方案

在小程序中,可使用mobx-miniprogram配合mobx-miniprogram-bindings实现全局数据共享。其中:

  • mobx-miniprogram用来创建Store实例对象
  • mobx-miniprogram-bindings用来把Store中的共享数据或方法绑定到组件或页面中使用

MobX相关包的安装

在项目中运行如下命令,安装MobX相关的包:

npm install --save mobx-miniprogram mobx-miniprogram-bindings

创建MobX的Store实例

import {observable,action} from 'mob-miniprogram'
export const store=observable({
numA:1,
numB:2,
//计算属性
get sum(){
return this.numA+this.numB
},
updateNum1:action(function(step){this.numA+=step}),
updateNum2:action(function(step){this.numB+=step})
})

将Store中的成员绑定到页面中

  • 绑定到页面
import {createStoreBindings} from 'mobx-miniprogram-bindings'
import {store} from '../../store/store'
Page({
onLoad:function(){
this.storeBindings=createStoreBindings(this,{
store,
fields:['numA','numB','sum'],
actions:['updateNum1']
})
},
onUnload:function(){
this.storeBindings.destroyStoreBindings()
}
})
  • 在页面中使用store成员
<view>{{mumA}}+{{numB}}={{sum}}</view>
<van-button type="primary" bindtap="btnHandler1" data-step="{{1}}">numA+1</van-button>
<van-button type="danger" bindtap="btnHandler1" data-step="{{-1}}">numA-1</van-button>
//按钮tap事件的处理函数
btnHandler1(e){
this.updateNum1(e.target.dataset.step)
}

将Store中的成员绑定到组件中

  • store挂载到组件上
import {storeBindingsBehavior} from 'mobx-miniprogram-bindings'
import {store} from '../../store/store'
Component({
behaviors:[storeBindingsBehavior], 
storeBindings:{
store,
fields:{
numA:()=>store.numA,
numB:(store)=>store.numB,
sum:'sum'
},
actions:{
updateNum2:'updateNum2'
}
}
})
  • 在组件中使用store
<view>{{numA}}+{{numB}}={{sum}}</view>
<van-button type="primary" bindtap="btnHandler2" data-step="{{1}}">numB+1</van-button>
<van-button type="danger" bindtap="btnHandler2" data-step="{{-1}}">numB-1</van-button>
//组件的方法列表
methods:{
btnHandler2(e){
this.updateNum2(e.target.dataset.step)
}
}
最后修改:2022 年 02 月 16 日
如果觉得我的文章对你有用,请随意赞赏