Javascript 如何在加载页面之前将数据从API提取到动态API URL(空值问题)
我是javascript和vue的初学者。我使用动态路由,并试图在页面加载时将数据从本地API(通过Apollo的Graphql)传递到Openweathermap API URL。问题是OpenWeatherAPI返回400,因为除非我刷新页面,否则URL会被传递一个空值(this.city)。在axios(或fetch)试图从openweather API获取任何数据之前,我一直无法确定如何从本地API获取值(城市名称) 简而言之:this.city作为空值传递给axios URL,该URL从API返回400错误,除非我刷新页面(这也不总是有效) 这是我的代码:Javascript 如何在加载页面之前将数据从API提取到动态API URL(空值问题),javascript,vue.js,graphql,nuxt.js,apollo,Javascript,Vue.js,Graphql,Nuxt.js,Apollo,我是javascript和vue的初学者。我使用动态路由,并试图在页面加载时将数据从本地API(通过Apollo的Graphql)传递到Openweathermap API URL。问题是OpenWeatherAPI返回400,因为除非我刷新页面,否则URL会被传递一个空值(this.city)。在axios(或fetch)试图从openweather API获取任何数据之前,我一直无法确定如何从本地API获取值(城市名称) 简而言之:this.city作为空值传递给axios URL,该URL
<script>
import venueQuery from '~/apollo/queries/venue/venue'
export default {
data() {
return {
loading: 0,
venues: [],
city: '',
sunset: '',
currentTemp: ''
}
},
apollo: {
$loadingKey: 'loading',
venues: {
prefetch: true,
query: venueQuery,
variables() {
return {
slug: this.$route.params.slug
}
},
result(result) {
return this.city = result.data.venues[0].temperature
}
}
},
created() {
this.getWeatherInfo()
},
methods: {
getWeatherInfo() {
this.$axios
.$get(`${process.env.WEATHER_BASEAPI}${this.city}${process.env.WEATHER_KEY}`).then(data => {
this.currentTemp = Math.floor(data.main.temp - 273.15);
this.sunset = new Date(data.sys.sunset * 1000).toLocaleTimeString("en-GB").slice(0, 5)
})
}
}
}
</script>
从“~/apollo/queries/venue/venueQuery”导入venueQuery
导出默认值{
数据(){
返回{
加载:0,
地点:[],
城市:'',
日落:'',
currentTemp:'
}
},
阿波罗:{
$loadingKey:“正在加载”,
场地:{
预回迁:对,
查询:venueQuery,
变量(){
返回{
slug:这个。$route.params.slug
}
},
结果(结果){
返回this.city=result.data.victions[0]。温度
}
}
},
创建(){
这是getWeatherInfo()
},
方法:{
getWeatherInfo(){
这是axios
.get(`process.env.WEATHER\u BASEAPI}${this.city}${process.env.WEATHER\u KEY}`)。然后(数据=>{
this.currentTemp=数学地板(data.main.temp-273.15);
this.sunset=新日期(data.sys.sunset*1000).toLocaleTimeString(“en GB”).slice(0,5)
})
}
}
}
任何帮助都将不胜感激。由于
city
在组件创建后异步填充,因此getWeatherInfo()
(在created
hook中)将在city
实际设置之前调用
您可以在city
上添加一个,以便对数据属性的任何更新都会导致getWeatherInfo()
:
导出默认值{
观察:{
城市(){
这是getWeatherInfo()
}
}
}