How to use axios response data in data function - vue

只谈情不闲聊 提交于 2019-12-11 18:32:29

问题


Using axios to fetch api data:

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

Data function:

  data () {
    return {
      offersData: {}
    }
  }

Now i can use fetched data in my template, like so: {{ offersData.item[0].id }}

But can i set the fetched data in a data function:

  data () {
    return {
      offersData: {},
      id: this.offersData.item[0].id
    }
  }

It's not working for me, is that even possible to store axios get's response in a data function?


回答1:


You probably are looking for computed property:

data () {
  return {
    offersData: {},
  }
},
computed() {
  id() {
    return this.offersData.item && this.offersData.item[0].id;
  }
}

As for data function, it is used to define shape of state (set up the properties to be tracked) of component and give valid initial values to it. In this case, however, id should neither be a part of state (it's always a part of offersData value, after all) nor its initial value can be calculated before offersData is set up by a remote call.



来源:https://stackoverflow.com/questions/52084578/how-to-use-axios-response-data-in-data-function-vue

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!