问题描述
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()
这个方法必须在你的业务如ajax执行完毕后再执行
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要添加async,否则编译不过去
async onLoad(option) {
//等待登录成功
await this.$onLaunched;
// 后续业务逻辑
},