【问题标题】:Async / Await on created method - Vue2创建方法中的异步/等待 - Vue 2
【发布时间】:2019-02-26 23:25:35
【问题描述】:

我有 vue-element-loading 包,在我的 page.vue 中添加了它的组件:

<vue-element-loading :active="isActive" :is-full-screen="true"/>

向数据添加变量:

data () {
  return {
    isActive: false,
  }
}

然后在页面完成加载时触发isActivetrue

async created () {
  this.isActive = true
  await this.fetchData()
  this.isActive = false
}

fetchData 是一个带有响应的 axios 获取请求。想法是显示加载程序,直到 axios 正确触发并获得响应。但是现在,我的加载器显示了 0.1 毫秒,然后消失了。

这是fetchData 方法:

fetchData () {
  axios.get(globalConfig.OFFERS_URL)
    .then((resp) => {
      this.offersData = resp.data
      console.log(resp)
    })
    .catch((err) => {
      console.log(err)
    })
},

【问题讨论】:

  • axios 只是返回缓存的结果吗?那会很快。
  • @MarkMeyer,我已经添加了我的方法,它会缓存吗?

标签: javascript vue.js axios


【解决方案1】:

看起来您的fetchData() 没有从对axios.get() 的调用中返回Promise,因此awaiting 会立即解决(即在axios.get() 完成之前)。

修复方法是返回axios.get()的结果:

fetchData() {
  return axios.get()
           .then(/*...*/)
           .catch(/*...*/);
}

【讨论】:

  • 谢谢,现在可以了。在我的情况下使用return 有什么问题吗? Promise.then,对吧?通过返回承诺,每个人都打算完全使用return 声明?
  • 我的意思是,我仍然没有得到 js 中 Promises 的概念,你能用简单的话解释一下吗?
  • 请看Promise docs
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-19
相关资源
最近更新 更多