How to use axios response data in data function -

2019-08-29 10:14发布

问题:

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.



标签: vue.js axios