uniapp中onLaunch异步方法与onLoad执行顺序问题

3 篇文章 0 订阅
2 篇文章 0 订阅

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;
  // 后续业务逻辑
}
  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值