微信小程序开发基础知识7----全局数据共享

一、简介

1、什么是全局数据共享

全局数据共享(又叫做:状态管理)是为了解决组件之间数据共享的问题。

开发中常用的全局数据共享方案有:Vuex、Redux、MobX等。

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

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

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

二、Mobx

1、安装MobX相关的包

在项目中打开PowerShell窗口,输入一下指令,安装Mobx相关包

npm install --save mobx-miniprogram@4.13.2 mobx-miniprogram-bindings@1.2.1
2、创建MobX的Store实例
import {observable, action} from 'mobx-miniprogram'

export const store = observale({
    //数据字段
    numA: 1,
    numB: 2,
    //计算属性
    get sum(){
        return this.numA + this.numB
    },
    //actions 方法,用来修改store中的数据
    updateNum1: action(function (step){
        this.numA += step
    }),
    updateNum2:action(function (step){
        this.numB += step
    }),
})
3、将Store中的成员绑定到也页面中
//页面的.js文件
import {cerateStoreBindings} from 'mobx-miniprigram-bindings'
import {store} from '../../store/store'

Page({
    onload:function(){ //生命周期函数--监听页面加载
        this.storeBindings = createStroreBindings(this,{
            store,
            fields:['numA','numB','sum'],
            actions:['updateNum1']
          })
    },
    onUnload:function(){ //生命周期函数--监控页面卸载
        this.storeBindings.destoryStoreBindings()
    }
})
4、在页面上使用Store中的成员
//页面的.wxml结构
<view>{{numA}} + {{numB}} = {{sum}}</view>
<van-button type="primary" bindtap="btnHandler1" data-step="{{1}}">
    numA + 1
</van-button>
<van-button type="dnager" bindtap="btnHandler1" data-step="{{-1}}">
    numA - 1
</van-button>

//按钮tap事件的处理函数
btnHandler1(e){
    this.updateNum1(e.target.dateset.step)
}
5、将Store中的成员绑定到组件中
import {storeBindingsBehavior} from 'mobx-miniprogram-bindings'
import {store} from '../../store/store'

Componnent({
    behaviors:[storeBindingsBehavior],//通过storeBindingsBehavior来实现自动绑定

    storeBindings:{
        store, //指定要绑定的Store
        fields:{ //指定要绑定的字段数据
            numA:()=>store.numA, //绑定字段的第1种方式
            numB:(store) => store.numB, //绑定字段的第2种方式
            sum:'sum'   //绑定字段的第3种方式
        },
        actions:{//指定要绑定的方法
            updateNum2:'updateNum2'
        }
    },
})
6、在组件中使用Store中的成员
//组件的.wxml结构
<view>{{numA}} + {{numB}} = {{sum}}</view>
<van-button type="primary" bindtap="btnHandler1" data-step="{{1}}">
    numB + 1
</van-button>
<van-button type="dnager" bindtap="btnHandler1" data-step="{{-1}}">
    numB - 1
</van-button>

//组件的方法列表
methods:{
    btnHandler2(e){
        this.updateNum2(e.target.dateset.step)
    }
}

  • 10
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值