uniapp 先执行onLaunch,再执行onLoad

问题描述

我们在用 uni-app 开发前端项目时,会遇到需要在 onLaunch 中请求接口返回结果,并且此结果在项目各个页面的 onLoad 中都有可能使用到的需求,比如微信小程序在 onLaunch 中进行登录后取得 openid 并获得 token,项目各页面需要带上该 token 请求其他接口。但是,onLaunch 中的请求是异步的,也就是说在执行 onLaunch 后页面 onLoad 就开始执行了,而不会等待 onLaunch 异步返回数据后再执行,这就导致了页面无法拿到 onLaunch 中异步获取的数据。

解决方案

main.js添加

Vue.prototype.$onLaunched = new Promise(resolve => {
    Vue.prototype.$isResolve = resolve
})

在 App.vue 的 onLaunch 中增加代码 this.$isResolve()

let that = this
setTimeout(function() {
    console.log('onLaunch执行完毕')
    that.$isResolve()
}, 3000);

在页面 onLoad 中增加代码 await this.$onLaunched

//onLoad 生命周期函数前,加async/await,用此方法同步执行顺序
async onLoad() {
    await this.$onLaunched
    console.log('onLoad')
}

 

总结

1. 先给onLaunch方法套一个promise实例,执行成功后再执行全局挂载的方法,标识当前已经执行完毕。
2. 在页面中利用async/await 同步执行代码的方法,实现onLaunch 在 onLoad 之后执行

 

posted @ 2022-11-24 15:41  Mr.木易  阅读(349)  评论(0编辑  收藏  举报