安装
文档 https://developers.weixin.qq.com/miniprogram/dev/extended/utils/mobx.html
//项目安装
npm install --save mobx-miniprogram mobx-miniprogram-bindings
工具——构建npm
创建文件store/index.js
import { observable, action } from 'mobx-miniprogram'
export const store = observable({
// 数据字段
userInfo: wx.getStorageSync('userInfo') || {},
num:1,
get sum(){
return 11
},
// actions方法
//方法一:接收接口返回的userinfo,全局存储
update: action(function (userInfo) {
this.userInfo = userInfo
wx.setStorage({
key: 'userInfo',
data: userInfo,
})
}),
//方法二:操作全局数据数据
changeNum:action(function(){
this.num=this.num + this.sum
}),
//方法三:接收参数,操作数据
changeData: action(function (a) {
this.num = this.num + a
})
})
组件中使用全局数据
//引入
import { storeBindingsBehavior } from 'mobx-miniprogram-bindings'
import { store } from '../../store/index.js'
// pages/my/my.js
Component({
behaviors: [storeBindingsBehavior], //注册
/**
* 页面的初始数据
*/
data: {
},
//只调取用到的数据和方法
//简写 fields: ['numA', 'numB', 'sum'],
//简写 actions: ['update'],
storeBindings: {
store,
fields: { //两种写法
num: () => store.num,
sum: 'sum'
},
actions: {
buttonTap: 'changeNum',
changeData1:'changeData'
},
},
methods:{
upnum(){
console.log(111);
this.changeData1(100); //给方法传递外部参数
}
}
})
<view class="my green">
<view class="top">你是不是傻{{num}}</view> //直接只用全局变量
<view class="bottom">不是吧 {{sum}}</view>
<button bindtap="buttonTap">点击</button> //调用全局方法
<van-button type="default">默认按钮</van-button>
<van-button type="primary" bindtap="upnum">主要按钮</van-button> //在方法里给全局方法传参
</view>