Axios Get API Call Causing Unexpected Behaviour

2019-08-02 05:41发布

问题:

My CodePen below is a working example of what should be happening. Everything there is working as expected. I am using hard coded data there.

CodePen: https://codepen.io/anon/pen/XxNORW?editors=0001

Hard coded data:

info:[
{
    "id": 1,
    "title": "Title one",
    "category_data": {
        "2": "Team",
        "7": "Queries"
    }
}
],

Issue:

When I replace the hard coded data with an AXIOS get call, the CodePen checkboxes do not function as expected. The All checkbox is correctly checked, however the rest are not.

I'm assuming, the slight delay in loading the API is the cause of this.

mounted() {
   this.getData(); 
},
methods: {
    getData: function() {
      axios
       .get('https://EXAMPLE.com/API/')
      .then(response => {
        this.info = response.data
        this.dataReady = true
      })
      .catch(error => {
        console.log(error)
       this.errored = true
  })
       .finally(() => this.loading = false)
    }
},

I do not load the front-end until the data is ready.

How can I remedy this issue?

Thanks.

回答1:

In your demo, calling select() asserts the "Select All" feature (checking all checkboxes), but those checkboxes aren't available until getData() resolves, so just move select() after getData():

async mounted() {
  await this.getData();
  this.select();
},
methods: {
  async getData() {
    const {data} = await axios.get(/* URL TO API DATA */);
    this.info = data;
  },
  // ...
}

demo



回答2:

While using axios inside your vue js application, you are using 'this' keyword inside axios which makes it confusing for compiler to which object your are trying to refer axios or vue, so to solve this problem try below code:

getData: function() {
   let app = this;
  axios
   .get('https://EXAMPLE.com/API/')
  .then(response => {
    app.info = response.data
    app.dataReady = true
  })
  .catch(error => {
    console.log(error)
   app.errored = true
  })
   .finally(() => app.loading = false)
  }

Hope this solves your problem.