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

网友投稿 458 2023-11-12

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

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

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

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

第一步:

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

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

第二步:

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

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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:

JS:

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

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

?
1
2
import {createStoreBindings} from mobx-miniprogram-bindings
import {store} from ../../libs/store.js
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Page({
behaviors:[storeBindingsBehavior],
storeBindings:{
// 数据源
store, //指定要绑定的store
fields:{//指定要绑定的字段数据
numA:()=>store.numA,     //绑定字段的第一种方式
numB:(store)=>store.numB,//绑定字段的第二种方式
sum:sum,               //绑定字段的第三种方式
},
actions:{ //指定要绑定的方法
updateNum2:updateNum2
}
},
})

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

?
1
2
3
4
//组件的 .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>
?
1
2
3
4
5
6
//组件的 .js结构
methods: {
btnHander2(e){
this.updateNum2(e.target.dataset.step)
}
}
您可能感兴趣的文章:微信小程序数据请求的方式和注意事项详解小程序中实现获取全部数据的图文教程微信小程序网络数据请求服务实现详解微信小程序前后端数据交互的详细图文教程微信小程序实现事件传参与数据同步流程详解微信小程序全局数据共享和分包图文详解微信小程序数据-使用实例详解

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:微信小程序天气预报功能实现(支持自动定位,附源码)
下一篇:开放银行生态是什么 - 了解银行业的未来发展趋势
相关文章

 发表评论

暂时没有评论,来抢沙发吧~