全局数据共享store的认识与使用

实现全局数据共享

小程序之间的数据共享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>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值