app.vue里的 onLaunch
中如果有异步方法(比如:登录),返回结果可能会在页面的 onLoad
之后,但 onLoad
中的方法需要登录回调的结果。
为了让页面的 onLoad
在 onLaunch
之后执行,解决方案:
1. main.js 添加代码
Vue.prototype.$onLaunched = new Promise(resolve => {
Vue.prototype.$isResolve = resolve;
})
2. 在 App.vue 的
onLaunch
中添加代码 this.$isResolve()
onLaunch: function() {
// 登录
uni.login({
provider: 'weixin',
success: (loginRes) => {
this.$axios({
url: '/xxxx/auth',
params: {
code: loginRes.code
}
}).then(res => {
try {
uni.setStorageSync('token', res.data.token);
this.$isResolve();
} catch (e) {
console.error(e)
}
})
}
});
}
3. 在页面
onLoad
中添加代码 await this.$onLaunched
async onLoad() {
// 等待登录结果返回
await this.$onLaunched;
// 处理后续业务逻辑(此时已存在token值)
console.log(uni.getStorageSync('token'));
this.getData();
},