Issue
How can I implement Axios? I went through the documentation but still not clear, thank you in advance, something to do with the API request from the weather site I presume
I only included the script part I hope that would be enough. My question is not debugging but how to simply replace the request part using axios.
<script>
export default {
name: 'app',
data() {
return {
api_key: 'f401be24a6ae97c3177533197510126c',
url_base: 'https://api.openweathermap.org/data/2.5/',
query: '',
weather: {}
}
},
methods: {
fetchWeather(e) {
if (e.key == "Enter") {
fetch(`${this.url_base}weather?q=${this.query}&units=metric&APPID=${this.api_key}`)
.then(res => {
return res.json();
}).then(this.setResults);
}
},
setResults(results) {
this.weather = results;
},
dateCreator() {
let dates = new Date();
let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
let days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
let day = days[dates.getDay()];
let date = dates.getDate();
let month = months[dates.getMonth()];
let year = dates.getFullYear();
return `${day} ${date} ${month} ${year}`;
}
}
}
</script>
Solution
Try like following snippet:
new Vue({
el: '#app',
data(){
return {
api_key :'f401be24a6ae97c3177533197510126c',
url_base: 'https://api.openweathermap.org/data/2.5/',
query:'',
weather:{}
}
},
methods: {
async fetchWeather () {
//if (e.key == "Enter") {
await axios(`${this.url_base}weather?q=${this.query}&units=metric&APPID=${this.api_key}`)
.then(res => this.weather = res.data);
//}
},
dateCreator () {
let dates = new Date();
let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
let days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
let day = days[dates.getDay()];
let date = dates.getDate();
let month = months[dates.getMonth()];
let year = dates.getFullYear();
return `${day} ${date} ${month} ${year}`;
}
},
mounted() {
if(this.query) this.fetchWeather()
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.22.0/axios.min.js" integrity="sha512-m2ssMAtdCEYGWXQ8hXVG4Q39uKYtbfaJL5QMTbhl2kc6vYyubrKHhr6aLLXW4ITeXSywQLn1AhsAaqrJl8Acfg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<div id="app">
<label>City name</label>
<input v-model="query" />
<button @click.prevent="fetchWeather">Show weather<button>
<p>{{ weather }}</p>
</div>
Answered By - Nikola Pavicevic Answer Checked By - Marie Seifert (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.