我在处理从远程API获取的数据时遇到了问题。
该应用程序正在使用Vuetify运行VueJS,数据是用Vuetify的数据表组件格式化的。
这是我的代码:
export default {
data () {
return {
headers: [
{ text: 'City', value: 'city' },
{ text: '#Citizens', value: 'citizens' },
{ text: '#Schools', value: 'schools' },
{ text: 'Schools per Citizen', value: 'schoolsPerCitizen' },
(...)
API URL被定义为应用程序根级别上的变量。
然后,当created()
启动时,会启动以下方法:
methods: {
loadData() {
axios.get(citiesApiUrl)
.then((response) => {
console.log(response.data) // data displayed correctly
return response.data
})
.catch(error => {console.error(error)})
}
},
created () {
this.loadData()
}
正如您在注释中注意到的,response.data
确实显示了所需的值。
问题从这一点开始:
computed: {
stats() {
return this.loadData().map(item => {
item.schoolsPerCitizen = (item.schools / item.citizens).toFixed(2)
return item
})
}
}
我得到一个错误:TypeError: Cannot read property 'map' of undefined
。
你知道我的代码出了什么问题吗?
问题
-
当在
created
中调用loadData
时,axios promise被消耗,但返回的数据除了被记录并返回到promise解析器之外,什么都没有发生。 -
当在
stats
(计算(中调用loadData
时,.map
与loadData
的返回值连锁,但loadData
没有返回值。 -
即使
loadData
返回axios promise,在访问数据(需要.then
(之前,该promise也必须首先在stats
中使用 -
设计是有缺陷的,因为计算的每次重新计算时都会发出相同的API调用,这可能是不必要的。
-
此外,
stats
返回的promise无论如何都不会被模板呈现函数解析。
修复
为加载的数据创建一个变量(我称之为mydata
(:
data() {
return {
// ...
mydata: []
}
}
将loadData
更改为:
loadData() {
axios.get(citiesApiUrl).then((response) => {
this.mydata = response.data // <--- Set the data to `mydata`
}).catch(error => {
console.error(error)
})
}
将stats
更改为:
stats() {
// This is also not designed properly, it's going to mutate `mydata`...
// You should study Vue and learn what the purpose for computeds are before using them
return this.mydata.map(item => { // <-- Once `mydata` is populated, this will recalculate
item.schoolsPerCitizen = (item.schools / item.citizens).toFixed(2)
return item
})
}
loadData不返回任何值。
loadData() {
return axios.get(citiesApiUrl)
.then((response) => {
console.log(response.data) // data displayed correctly
return response.data
})
.catch(error => {console.error(error)})
}