vue/uniapp 如何让页面的 onLoad 在 onLaunch 之后执行[通俗易懂]

app.vue里的onLaunch中如果有异步方法(比如:登录),返回结果可能会在页面的onLoad之后,但onLoad中的方法需要登录回调的结果。为了让页面的onLoad在onLaunch之后执行,解决方案:1.main.js添加代码Vue.prototype.$onLaunched=newPromise(resolve=>{Vue.prototype.$isResolve=resolve;})2.在App.vue的onLau

大家好,又见面了,我是你们的朋友全栈君。

app.vue里的 onLaunch 中如果有异步方法(比如:登录),返回结果可能会在页面的 onLoad 之后,但 onLoad 中的方法需要登录回调的结果。

为了让页面的 onLoadonLaunch 之后执行,解决方案:

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();
},
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/129636.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号