微信小程序中使用mobx
最近在做微信小程序的项目,由于在react项目中使用mobx作为状态管理工具,所有也想在小程序项目中使用mobx为项目做数据驱动。下面的内容将介绍如何在微信小程序项目中使用mobx。
一、引入mobx
1、clone或者下载代码包到本地
https://github.com/ck1642705415/mobx-weapp.
2、将 mobx.js 和 observer.js 和 diff.js 三个文件拷贝到项目中(本人是把文件放在mobx文件夹下)
3、创建store目录,统一存放项目中所有的数据层文件
4、创建store文件
import {decorate, observable, action, runInAction} from '../mobx/mobx.js'
class TestStore = {
username = null // observable data
// action
setUserName = () => {
console.log(this.username)
}
}
const testStore = new TestStore()
export {testStore, TestStore}
小程序不支持 @decorate 装饰器,但是mobx.js中提供了decorate方法,我们对TestStore做一层装饰。
完整代码如下:
import {decorate, observable, action, runInAction} from '../mobx/mobx.js'
class TestStore = {
username = null // observable data
// action
setUserName = () => {
console.log(this.username)
}
}
decorate(TestStore, {
username: observable,
setUserName: action
})
const testStore = new TestStore()
export {testStore, TestStore}
5、页面中使用store
在用store之前,我们首先在store目录下创建index.js文件,用于导出store目录下所有的store文件
export { testStore} from './testStore.js'
// ...
全局引入store,在app.js文件中导入,注意App内部要用observer包裹,并在globalData中定义store
import {
observer
} from './mobx/observer.js'
import * as store from './store/index.js'
App(observer({
globalData: {
store: { ...store }
},
onLaunch: async function() {
},
onHide: function() {
}
}))
引入好之后,我们要在页面js文件中使用store了,和app.js一样,要先对Page内部用observer进入包装,之后拿到globalData中对应的store,并在props中引入,此处要注意:store必须放在props中,否则会拿不到store中的数据及方法。
// pages/coupons/coupons.js
import {
observer
} from '../../mobx/observer.js'
const app = getApp()
const store = app.globalData.store.testStore
Page(observer({
props: {
store: store
},
/**
* 页面的初始数据
*/
data: {
},
changeName(){
this.props.store.setUserName()
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
},
}))
<view>
<text>{{props.store.username}}</text>
<button bindtap="changeName">设置userName</button>
</view>