全局数据共享 全局数据共享(状态管理)是为了解决组件之间数据共享的问题,开发中常用的全局数据共享方案有: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

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

第二步:
在根目录下创建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 成员绑定到组件中----------------------------
- 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)
- }
- }
到此这篇关于微信小程序中使用store数据共享的文章就介绍到这了,更多相关小程序store数据共享内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!