最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - AsyncAwait on created method - Vue2 - Stack Overflow

programmeradmin3浏览0评论

I have vue-element-loading package, added it's ponent in my page.vue:

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

Added variable to data:

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

Then triggering isActive to true when the page finishes load:

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

fetchData is an axios get request with response. Idea is to show loader, till axios properly fires and getting response. But now, my loader shows for 0.1 milliseconds, then disappears.

Here's the fetchData method:

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

I have vue-element-loading package, added it's ponent in my page.vue:

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

Added variable to data:

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

Then triggering isActive to true when the page finishes load:

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

fetchData is an axios get request with response. Idea is to show loader, till axios properly fires and getting response. But now, my loader shows for 0.1 milliseconds, then disappears.

Here's the fetchData method:

fetchData () {
  axios.get(globalConfig.OFFERS_URL)
    .then((resp) => {
      this.offersData = resp.data
      console.log(resp)
    })
    .catch((err) => {
      console.log(err)
    })
},
Share Improve this question edited Sep 23, 2018 at 3:01 Alexander Kim asked Sep 23, 2018 at 2:59 Alexander KimAlexander Kim 18.4k24 gold badges107 silver badges165 bronze badges 2
  • Is axios just returning cached results? That would be very quick. – Mark Commented Sep 23, 2018 at 3:00
  • @MarkMeyer, i've added my method, does it cache at all? – Alexander Kim Commented Sep 23, 2018 at 3:02
Add a ment  | 

1 Answer 1

Reset to default 4

It looks like your fetchData() doesn't return the Promise from the call to axios.get(), so awaiting it would resolve immediately (i.e., before the axios.get() pletes).

The fix is to return the result of axios.get():

fetchData() {
  return axios.get()
           .then(/*...*/)
           .catch(/*...*/);
}
发布评论

评论列表(0)

  1. 暂无评论