微信小程序中使用mobx

微信小程序中使用mobx

最近在做微信小程序的项目,由于在react项目中使用mobx作为状态管理工具,所有也想在小程序项目中使用mobx为项目做数据驱动。下面的内容将介绍如何在微信小程序项目中使用mobx。

一、引入mobx

1、clone或者下载代码包到本地
https://github.com/ck1642705415/mobx-weapp.

2、将 mobx.jsobserver.jsdiff.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>

本文结束,感谢观看!

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值