PHP菜鸟博客_共同学习分享PHP技术心得【PHP爱好者】
uni-app在onLaunch中异步调用接口获取到返回值后执行onload
2021-7-14 菜鸟站长


问题描述:



项目启动调用接口根据当前的域名获取到一个sys_id的参数,后续onload里面所有接口的调用都需要携带参数sys_id。但是,onLaunch 中的请求是异步的,也就是说在执行 onLaunch 后页面 onLoad 就开始执行了,而不会等待 onLaunch 异步返回数据后再执行,这就导致了页面无法拿到 onLaunch 中异步获取的数据。



解决方案:



步骤1



在 main.js 中增加如下代码:



Vue.prototype.$onLaunched = new Promise(resolve => {
Vue.prototype.$isResolve = resolve
})

1.jpg



步骤2

在 App.vue 的 onLaunch 中增加代码 this.$isResolve(),具体如下:



   this.$isResolve()

2.jpg



步骤3

在页面 onLoad 中增加代码 await this.$onLaunched,具体如下:



 await this.$onLaunched

3.jpg

评论:
小生
2021-11-20 11:50 回复
main.js 中
Vue.prototype.$onlaunched = new Promise (resolve=>{

Vue.prototype.$isResolve = resolve
})

app.vue中
// 微信
wx.login({

success:(res)=> { // 获取code if(res.code){ if(false){ uni.setStorageSync('isbinding',false) }else{ uni.setStorageSync('isbinding',true) } this.$isResolve(); console.log(res) }else{ console.log('登录失败!',res.errMsg) }
}
})

index.vue 中
data()
async onload(){
await that.$onlaunched
that.isbinding = uni.getStorageSync('isbinding')
}
这样写会有一个不到一秒的抖动 that.isbinding的值会先为false 再变为true
而根据这个变量判断页面是否显示 刚开始半秒的时间不显示,然后才显示
发表评论:
昵称

邮件地址 (选填)

个人主页 (选填)

内容