微信小程序状态管理
方案一:
将全局状态放在app.js
文件的globalData
中;
使用getApp().globalData
获取数据;
缺点:数据不是响应式
https://developers.weixin.qq.com/miniprogram/dev/reference/api/getApp.html
方案二:
使用第三方库hy-event-store
:
https://github.com/coderwhy/hy-event-store
npm i hy-event-store
使用库
store_a.js
import { HYEventStore } from 'hy-event-store'
const aStore = new HYEventStore({
state: {
a: {name:'coder'},
},
actions: {
async getRankingDataAction(ctx) {
console.log(11)
let pro = await new Promise((res, rej) => {
setTimeout(() => {
res("haha")
ctx.a = {name: 'xiuluo'}
},3000)
})
console.log(pro)
console.log('haha2')
}
}
})
export {
aStore
}
index.js
export * from './store_a'
页面引入index.js
import { aStore } from "../../store/index.js";
...
// 发起共享数据的请求
aStore.dispatch('getRankingDataAction')
// 从store获取共享的数据
aStore.onState("a", (res) => {
console.log(res.name)
})
1
1
1
1
1
1
1
1
1
1