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 @   Mr.木易  阅读(516)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示