Javascript Axios Get API调用导致意外行为
下面我的代码笔是一个应该发生的工作示例。那里的一切都按预期进行。我在那里使用硬编码数据 代码笔: 硬编码数据:Javascript Axios Get API调用导致意外行为,javascript,vue.js,vuejs2,axios,Javascript,Vue.js,Vuejs2,Axios,下面我的代码笔是一个应该发生的工作示例。那里的一切都按预期进行。我在那里使用硬编码数据 代码笔: 硬编码数据: info:[ { "id": 1, "title": "Title one", "category_data": { "2": "Team", "7": "Queries" } } ], 问题: info:[ { "id": 1, "title": "Title one", "category_d
info:[
{
"id": 1,
"title": "Title one",
"category_data": {
"2": "Team",
"7": "Queries"
}
}
],
问题:
info:[
{
"id": 1,
"title": "Title one",
"category_data": {
"2": "Team",
"7": "Queries"
}
}
],
当我用AXIOS get调用替换硬编码数据时,CodePen复选框无法按预期工作。所有复选框被正确选中,但其余的复选框未被正确选中
我假设,加载API的轻微延迟是造成这种情况的原因
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)
}
},
在数据准备就绪之前,我不会加载前端
我如何解决这个问题
谢谢。在您的vue js应用程序中使用axios时,您在axios中使用了'this'关键字,这会使编译器混淆您试图引用的对象是axios还是vue,因此要解决此问题,请尝试以下代码:
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)
}
希望这能解决您的问题。在您的演示中,调用
select()
会断言“全选”功能(选中所有复选框),但这些复选框在getData()
解决之前不可用,所以只需在getData()
之后移动select()
:
谢谢,我是否仍然会在该函数之外返回主信息变量this.info或app.info的数据?是的,您仍然会在该函数之外返回变量this.info或app.info:)您如何获得此知识级别…谢谢。