JS — Ajax request with axios

blossom0417
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

--

--

No responses yet