Axios获取导致意外行为的API调用 [英] Axios Get API Call Causing Unexpected Behaviour

查看:96
本文介绍了Axios获取导致意外行为的API调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的我的CodePen是应该发生的工作示例.那里的一切都按预期工作.我在那里使用硬编码数据.

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

硬编码数据:

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

问题:

当我用AXIOS get调用替换硬编码数据时,CodePen复选框无法正常工作. 全部复选框已正确选中,但其余的没有.

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.

我假设,加载API的时间稍有延迟是造成此问题的原因.

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.

如何解决此问题?

谢谢.

推荐答案

在您的演示中,调用select()会断言全选"功能(选中所有复选框),但是直到getData()解析后,这些复选框才可用,因此只需将select()移到getData()之后:

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;
  },
  // ...
}

演示

这篇关于Axios获取导致意外行为的API调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆