如何将来自axios的数据放入vue js数据:value: [parseInt(this.maintemp1),parseInt( this.maintemp2)], <--------Here is my problem
export default {
data: () => ({
maincity: "",
maintemp1: "",
maintemp2: "",
maindate1: "",
showLabels: true,
lineWidth: 2,
labelSize: 7,
radius: 10,
padding: 8,
lineCap: "round",
gradient: gradients[5],
value: [parseInt(this.maintemp1),parseInt( this.maintemp2)], <--------Here is my problem
gradientDirection: "top",
gradients,
fill: true,
type: "trend",
autoLineWidth: false
}),
mounted() {
axios
.get(
"http://api.openweathermap.org/data/2.5/forecast?q=khiva&units=metric&appid=myapi"
)
.then(response => {
this.wholeResponse = response.data.Search;
this.maincity = response.data.city.name;
this.maindate1 = response.data.list[1].dt_txt;
this.maintemp1 = response.data.list[1].main.temp;
this.maintemp2 = response.data.list[9].main.temp;
})
.catch(error => {
console.log(error);
});
}
};
答案 0 :(得分:0)
您的value
是一个计算属性。 data
包含可以在组件中随时间变化的静态事物的列表,但它们仍然仅仅是值。如果您的媒体资源动态依赖于其他媒体资源,则应将其放在computed
中,如下所示:
export default {
data: () => ({
maincity: "",
maintemp1: "",
maintemp2: "",
maindate1: "",
showLabels: true,
lineWidth: 2,
labelSize: 7,
radius: 10,
padding: 8,
lineCap: "round",
gradient: gradients[5],
gradientDirection: "top",
gradients,
fill: true,
type: "trend",
autoLineWidth: false
}),
computed: {
value() {
return [parseInt(this.maintemp1),parseInt( this.maintemp2)],
}
},
mounted() {
axios
.get(
"http://api.openweathermap.org/data/2.5/forecast?q=khiva&units=metric&appid=myapi"
)
.then(response => {
this.wholeResponse = response.data.Search;
this.maincity = response.data.city.name;
this.maindate1 = response.data.list[1].dt_txt;
this.maintemp1 = response.data.list[1].main.temp;
this.maintemp2 = response.data.list[9].main.temp;
})
.catch(error => {
console.log(error);
});
}
};
答案 1 :(得分:0)
之所以会发生这种情况,是因为甚至在调用data
方法之前都会对mounted
个选项值进行评估。因此,最初设置value
时,maintemp1
和maintemp2
是空字符串。另外,value
在这里不是计算属性,因此也不会跟踪maintemp1
和maintemp2
的更改。一种选择是在axios value
方法内设置.then()
。
因此,首先将value
设置为data
中的空数组,例如:
data: () => ({
...
value: [],
..
}),
然后在mounted
内部进行更新,例如:
axios
.get(
"http://api.openweathermap.org/data/2.5/forecast?q=khiva&units=metric&appid=myapi"
)
.then(response => {
this.wholeResponse = response.data.Search;
this.maincity = response.data.city.name;
this.maindate1 = response.data.list[1].dt_txt;
this.maintemp1 = response.data.list[1].main.temp;
this.maintemp2 = response.data.list[9].main.temp;
this.value = [parseInt(this.maintemp1), parseInt( this.maintemp2)];
})
.catch(error => {
console.log(error);
});