uniapp中onLaunch异步方法与onLoad执行顺序问题
问题描述:
uniapp中,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: function() {
const that = this
// #ifdef MP-WEIXIN
uni.getProvider({
service: 'oauth', // 授权登陆
success(res) {
if(res.provider.indexOf('weixin') > -1) {
// 微信小程序获取code码
uni.login({
provider: 'weixin',
success(wres) {
// 用code码换取openId、unionid、sessionKey等
loginByWechatCode({code: wres.code}).then(login => {
try {
// console.log('loginmm', login)
// 将登陆信息存入Vuex中
that.$store.commit("setLoginInfo", login.data)
if(login.code == 0) {
that.$isResolve()
uni.setStorageSync('talents_token', login.data.talents_token)
uni.switchTab({
url: '/pages/meeting/meeting'
})
} else if (login.code == 1002) { // 用户未绑定,跳转到授权手机号页面
uni.showModal({
title: '提示',
content: '您还未绑定手机号,是否现在去绑定?',
showCancel: false,
success (res) {
if(res.confirm) {
uni.redirectTo({
url: '/pages/login/LoginPage'
})
}
}
})
} else { // 状态异常
that.$store.commit("set_user_statu", login)
}
} catch(e) {
console.error(e)
}
})
}
})
}
}
})
// #endif
},
3、在页面 onLoad 中增加代码 await this.$onLaunched
注意onload要添加async,否则编译不过去
async onLoad(option) {
//等待登录成功
await this.$onLaunched;
// 后续业务逻辑
}