JS — Ajax request with axios
1 min readOct 1, 2018
<button class="button" type="button" name="button" @click="fetchPosts">fetch data</button>
<div class="" v-for="post in posts" :key="post.id">
<h2>{{post.title}}</h2>
<p>{{post.body}}</p>
</div>
#script
export default {
name : 'placeholder',
data(){
return {
posts:[],
loading: false,
errored: false
}
},
// mounted () {
// $http
// .get('https://jsonplaceholder.typicode.com/posts')
// .then(response => {
// this.posts = response.data
// })
// .catch(error => {
// console.log(error)
// this.errored = true
// })
// .finally(() => this.loading = false)
// }
methods:{
fetchPosts(){
this.loading = true;
// using JSONPlaceholder
const baseURI = 'https://jsonplaceholder.typicode.com';
this.$http.get(`${baseURI}/posts`)
.then((response) => {
console.log(response)
this.loading = false;
this.posts = response.data
})
.catch(error => {
console.log(error)
this.loading = false;
this.errored = true
})
//.finally(() => this.loading = false)}
}
}
#example
axios.get(url)
.then((response) => {
document.querySelector('.panel').innerHTML= response.data.results.map(function(item,index){
console.log(item)
return (
`<li> ${index} :
${item.gender} , ${item.name.first} ${item.name.last}</li>`
);
}).join('');
})
.catch(function(error) {
const message = 'errored!'
console.log('errored')
document.getElementById('panel').innerHTML = '<h2 class="text-danger">' + message + '</h2>';
// If there is any error you will catch them here
});
#reference
- https://medium.com/techtrument/handling-ajax-request-in-vue-applications-using-axios-1d26c47fab0
- https://vuejs.org/v2/cookbook/using-axios-to-consume-apis.html#Displaying-Data-from-an-API
- https://alligator.io/vuejs/rest-api-axios/
- https://scotch.io/tutorials/how-to-use-the-javascript-fetch-api-to-get-data
- https://opentutorials.org/course/3281/20562
- https://github.com/axios/axios
- https://github.com/axios/axios/blob/master/examples/get/index.html