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();
},