uni-app在onLaunch中异步调用接口获取到返回值后执行onload

  • 内容
  • 评论
  • 相关

问题描述:

项目启动调用接口根据当前的域名获取到一个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

本文标签:

版权声明:若无特殊注明,本文皆为《菜鸟站长》原创,转载请保留文章出处。

本文链接:uni-app在onLaunch中异步调用接口获取到返回值后执行onload - http://wziyi.com.cn/?post=279

发表评论

电子邮件地址不会被公开。 必填项已用*标注

评论

1条评论
  1. avatar

    小生 Lv.1 回复

    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
    而根据这个变量判断页面是否显示 刚开始半秒的时间不显示,然后才显示

    IP数据库文件不存在或者禁止访问或者已经被删除!