问题描述
我们在用 uni-app 开发前端项目时,会遇到需要在 onLaunch 中请求接口返回结果,并且此结果在项目各个页面的 onLoad 中都有可能使用到的需求,比如微信小程序在 onLaunch 中进行登录后取得 openid 并获得 token,项目各页面需要带上该 token 请求其他接口。但是,onLaunch 中的请求是异步的,也就是说在执行 onLaunch 后页面 onLoad 就开始执行了,而不会等待 onLaunch 异步返回数据后再执行,这就导致了页面无法拿到 onLaunch 中异步获取的数据。
解决方案
步骤1
在 main.js 中增加如下代码:
Vue.prototype.$onLaunched = new Promise(resolve => { Vue.prototype.$isResolve = resolve })
步骤2
在 App.vue 的 onLaunch
中增加代码 this.$isResolve()
,具体如下:
onLaunch () {
// #ifndef H5 uni.login({ success: loginRes => { // #ifdef MP-WEIXIN login({ // 该接口为我们自己写的获取 openid/token 的接口,请替换成自己的 appId: 'wx1234567890', code: loginRes.code }).then(res => { try { console.info(res.object.token) uni.setStorageSync('mcToken', res.object.token) this.$isResolve() } catch (e) { console.error(e) } }) // #endif } }) // #endif }
步骤3
在页面 onLoad
中增加代码 await this.$onLaunched
,具体如下:
async onLoad(option) { await this.$onLaunched let token = '' try { token = uni.getStorageSync('mcToken') } catch(e) { console.error(e) } // 下面就可以使用 token 调用其他相关接口 }
版权属于:瞭月
本文链接:https://www.lervor.com/archives/128/
版权声明:本文为瞭月原创文章,转载请附上原文出处链接和本声明。