我是Vue的新手,並且正在開發一款應用程序以從天氣api獲取天氣。
下面的代碼工作,如果我離開axios.get()
在Content.vue
如下所示。
我想將它移動到一個單獨的文件(WeatherAPI.js
)並從那裏調用它。如果我在Content.vue
中撥打電話axois.get()
,並取消註釋this.todaysWeather = WeatherAPI.returnTodaysWeather();
,則不起作用。我確實看到從WeatherAPI.js
記錄到控制檯的數據,所以它得到它,但似乎沒有正確返回它。我在Content.vue
的控制檯日誌中看到undefined
。Vuejs從.js文件返回數據
Content.vue
<template>
<div class="container-fluid">
<div class="row answerRow text-center">
<div class="col">
</div>
</div>
<div class="row">
<div class="col">
<weather-today :todaysWeather="todaysWeather"></weather-today>
</div>
<div class="col">
Column2
</div>
</div>
</div>
</template>
<script>
import Today from '../weather/Today.vue'
import WeatherAPI from '../data/WeatherAPI.js'
import axios from 'axios'
const apiURL = "http://api.openweathermap.org/data/2.5/weather";
const apiKey = "MyKeyHere";
const zipCode = "11111,us";
const dailyWeatherUrl = apiURL + "?zip=" + zipCode + "&appid=" + apiKey;
export default {
mounted(){
this.getTodaysWeather();
console.log(this.todaysWeather)
},
data() {
return {
todaysWeather: {name: "testname"}
}
},
components: {
'weather-today': Today
},
methods: {
getTodaysWeather() {
//this.todaysWeather = WeatherAPI.returnTodaysWeather();
axios.get(dailyWeatherUrl)
.then((response) => {
console.log(response.data);
this.todaysWeather = response.data;
})
.catch(function (error) {
console.log(error);
});
}
}
}
</script>
<style>
.answerRow{
background-color: yellow;
}
</style>
Today.vue
<template>
<div class="container row1">
<div class="row">
<div class="col">
<h2>Todays Weather</h2>
</div>
</div>
<div class="row">
<div class="col">
City: {{ todaysWeather.name }}
</div>
</div>
</div>
</template>
<script>
import WeatherAPI from '../data/WeatherAPI.js'
export default {
props: ['todaysWeather'],
mounted() {
console.log(this.todaysWeather)
}
}
</script>
<style>
.row1{
background-color: #3498DB;
}
</style>
WeatherAPI.js
const apiURL = "http://api.openweathermap.org/data/2.5/weather";
const apiKey = "MyKeyHere";
const zipCode = "11111,us";
const dailyWeatherUrl = apiURL + "?zip=" + zipCode + "&appid=" + apiKey;
import axios from 'axios';
export default {
data(){
return {
todaysWeather: {}
}
},
returnTodaysWeather() {
axios.get(dailyWeatherUrl)
.then((response) => {
console.log(response.data);
this.todaysWeather = response.data;
console.log(this.todaysWeather);
return this.todaysWeather;
})
.catch(function (error) {
console.log(error);
});
}
}