问题描述
app.vue里的onLaunch中如果有异步方法,返回结果可能会在页面的 onLoad 之后,为了让页面的 onLoad 在 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,具体如下:
onLoad(option) {
await this.$onLaunched
let token = ''
try {
token = uni.getStorageSync('mcToken')
} catch(e) {
console.error(e)
}
// 下面就可以使用 token 调用其他相关接口
}
任何页面的 onLoad 需要在 onLaunch 完成后执行的,都要加这段;