全局数据共享 全局数据共享(状态管理)是为了解决组件之间数据共享的问题,开发中常用的全局数据共享方案有:Vuex、Redux、MobX等

在小程序中,可用 mobx-miniprogram (用来创建 Store 实例对象) 配合 mobx-miniprogram-bindings (用来把 Store 中的共享数据或方法,绑定到组件和页面中使用)实现全局数据共享

安装 MobX 相关的包 在项目中运行如下命令,安装 MobX相关的包:(注意要启用管理员权限) 安装完成重新构建 npm

第一步:

npm install --save mobx-miniprogram@4.13.2 mobx-miniprogram-bindings@1.2.1

微信小程序中如何使用store数据共享

安装完成后选择:工具-》构建npm

微信小程序中如何使用store数据共享

第二步:

在根目录下创建store文件夹,并在其中创建store.js文件

在这个 JS 文件中,专门来创建 Store 的实例对象

import {observable,action} from 'mobx-miniprogram' 
 
export const store = observable({ //2、创建共享数据,并向外暴露出去
    //定义数据字段
    namesValue:'文龙刚',
    shopCarTotalCount:0,//购物车数量
    sitesPosition:wx.getStorageSync('sitesInfo')||'',//提货点
    RestDay:true,
 
    shopTotalCount:action(function(step){//购物车总数
        console.log('传递过来的值是:',step)
        this.shopCarTotalCount+=step
    }),
    setSitesPosition:action(function(position){//设置提货点
      this.sitesPosition=position
    }),
    getRestDay:action(function(type){
      this.RestDay=!this.RestDay
    })
})

 第三步:将 Store 中的成员绑定到页面中

wxml:

<view>
  <!-- 这是调用参数的方法 -->
  <view>
    namesValue:{{namesValue}}
  </view>
  <!-- 这是调用方法的 -->
  <view>
    购物车数量:{{shopCarTotalCount}}
  </view>
  <view>
    <button bindtap="addShopCarTotalCount" data-step='1'>增加</button>
  </view>
 
  <!-- 更改状态 -->
  <view>
    当前状态:{{RestDay}}
  </view>
  <button bindtap="changeType">更改状态</button>
</view>

JS:

import {createStoreBindings} from 'mobx-miniprogram-bindings'
import {store} from '../../libs/store.js'
//因为我是将store.js文件放在libs中了
Page({
    onLoad(options) {
        //第二步:这是store中参数及方法的导入
        this.storeBindings = createStoreBindings(this, {
            store,
            fields: ['namesValue','shopCarTotalCount', 'RestDay', 'sitesPosition'],
            actions: ['shopTotalCount',  'setSitesPosition','getRestDay'],
        })
  },
 
})

微信小程序中如何使用store数据共享

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

import {createStoreBindings} from 'mobx-miniprogram-bindings'
import {store} from '../../libs/store.js'
Page({
  behaviors:[storeBindingsBehavior],
  storeBindings:{
    // 数据源
    store, //指定要绑定的store
    fields:{//指定要绑定的字段数据
      numA:()=>store.numA,     //绑定字段的第一种方式
      numB:(store)=>store.numB,//绑定字段的第二种方式
      sum:'sum',               //绑定字段的第三种方式
    },
    actions:{ //指定要绑定的方法
      updateNum2:'updateNum2'
    }
  },
})

---------------------------------在组件中使用 Store 中的成员---------------------------------

//组件的 .wxml结构
<view>{{numA}}+{{numB}}={{sum}}</view>
<van-button type="primary" bindtap="btnHander2" data-step="{{1}}">numB+1</van-button>
<van-button type="danger" bindtap="btnHander2" data-step="{{-1}}">numB-1</van-button>
//组件的 .js结构
methods: {
  btnHander2(e){
    this.updateNum2(e.target.dataset.step)
  }
}
原文地址:https://blog.csdn.net/qq_17211063/article/details/130077335

相关文章: