在小程序开发中,有时候会需要进行全局数据共享,在vue中有vuex进行数据共享,而小程序中也可以进行数据共享,在小程序中使用mobx进行数据共享,在进行数据共享前,先安装以下工具:
npm install --save mobx-miniprogram@版本 mobx-miniprogram-bindings@版本
然后进行构建,将以上两个安装包添加到node_module里面,然后在根目录创建store文件夹,在文件夹下创建store.js文件,编辑store.js文件如下
// 在这个js文件中,专门来创建store的实例对象
import {observable,action} from 'mobx-miniprogram'
export const store=observable({
// 数据字段
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
})
})
在页面js文件中使用store中的数据:
// pages/message/message.js
import {createStoreBindings} from 'mobx-miniprogram-bindings'
import {store} from '../../store/store'
Page({
/**
* 页面的初始数据
*/
data: {
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
this.storeBindings=createStoreBindings(this,{
store,
fields:['numA','numB','sum'],//store中的共享数据
actions:['updateNum1','updateNum2']
})
},
// btnHandler1事件处理函数
btnHandler1(e){
this.updateNum1(e.target.dataset.step)
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
this.storeBindings.destoryStoreBindings()
},
})
在组件js文件中使用store中的数据:
// components/numbers/numbers.js
import { storeBindingsBehavior } from "mobx-miniprogram-bindings"
import {store} from '../../store/store';
Component({
behaviors:[storeBindingsBehavior],
storeBindings:{
// 数据源
store,
fields:{
//三种store数据引入方式
numA: () => store.numA,
numB: (store) => store.numB,
sum: "sum",
},
},
actions:{
updateNum2:'updateNum2'
},
},
/**
* 组件的方法列表
*/
methods: {
btnHandler2(e){
this.updateNum2(e.target.dataset.step)
}
}
})
在.xml页面中渲染数据:
<!--components/numbers/numbers.wxml-->
<!-- <text>components/numbers/numbers.wxml</text> -->
<view>{{numA}}+{{numB}}={{sum}}</view>
<van-button type="primary" bindtap="btnHandler2" data-step='{{1}}'>numB+1</van-button>
<van-button type="danger" bindtap="btnHandler2" data-step='{{-1}}'>numB-1</van-button>
最后的最后:一定一定一定不要拼错单词!!血的教训!!!在组件中使用时,因为拼错的单词以为是因为更新所以用不了了!!!!!!!!!真的真的真的不要拼错单词555555