实现全局数据共享
小程序之间的数据共享11
通过action方法修改store的值
使用store
//首先创建store文件
import {observable,action} from 'mobx-miniprogram'
export const store =observable({
num1:1,
num2:2,
updatenum1:action (function(step){
this.num1+=step
}),
updatenum2:action(function(step){
this.num2+=step;
})
})
//在使用store的页面的js文件中引入 onload方法 unOnload方法
import {createStoreBindings} from 'mobx-miniprogram-bindings'
import {store} from '../../store/store'
onLoad: function (options) {
this.storeBindings=createStoreBindings(this,{
store,
fields:['num1','num2'],
actions:['updatenum1','updatenum2']
})
},
onUnload: function () {
this.storeBindings.destroyStoreBindings();
},
//store使用 用{{}}即可
<view>{{num1}}</view>
使用方法 页面wxml
<view>{{num1}} + {{num2}} = {{sum}}</view>
<van-button type="primary" bindtap="addN1" data-step="{{1}}">num1+1</van-button>
<van-button type="danger" bindtap="addN2" data-step="{{1}}">num2+1</van-button>
页面js
addN1(e){
this.updatenum1(e.target.dataset.step)
},
addN2(e){
this.updatenum2(e.target.dataset.step)
},
store.js
import {observable,action} from 'mobx-miniprogram'
export const store =observable({
num1:1,
num2:2,
sum:3,
updatenum1:action (function(step){
this.num1+=step;
this.sum+=step;
}),
updatenum2:action(function(step){
this.num2+=step;
this.sum+=step;
})
})
组件中使用store
在组件中使用store中的成员
test组件中js
import {storeBindingsBehavior} from 'mobx-miniprogram-bindings'
import {store} from "../../store/store"
// components/test/test.js
Component({
behaviors:[storeBindingsBehavior],
storeBindings:{
store,
fields:{
num1:'num1',
num2:'num2',
sum:'sum'
},
actions:{
updatenum1:'updatenum1'
}
},
})
test组件中wxml
<view>我是自定义组件test {{num1}} + {{num2}} = {{sum}} </view>
<view>count的值为:{{count2}}</view>
<button bindtap="addNum">+1按钮</button>
使用组件 在页面json文件中
"usingComponents": {
"mytest1":"/components/test/test"
}
页面中使用wxml
<mytest1></mytest1>