问题描述
使用axios提取api数据:
fetchData () {
axios.get(globalConfig.OFFERS_URL)
.then((resp) => {
this.offersData = resp.data
console.log(resp)
})
.catch((err) => {
console.log(err)
})
}
数据功能:
data () {
return {
offersData: {}
}
}
现在,我可以在模板中使用提取的数据,如下所示:{{ offersData.item[0].id }}
但是我可以在数据函数中设置获取的数据吗?
data () {
return {
offersData: {},
id: this.offersData.item[0].id
}
}
这对我不起作用,是否有可能将axios get的响应存储在数据函数中?
您可能正在寻找计算属性:
data () {
return {
offersData: {},
}
},
computed() {
id() {
return this.offersData.item && this.offersData.item[0].id;
}
}
对于数据功能,它用于定义组件的状态形状(设置要跟踪的属性)并为其提供有效的初始值.但是,在这种情况下,id
既不应该是状态的一部分(毕竟始终是offersData
值的一部分),也不能在通过远程调用设置offersData
之前计算其初始值./p>
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?
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.
这篇关于如何在数据功能中使用axios响应数据-Vue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!