Using Axios in Vue.js
Vue.js + Axios tutorial for beginner

Axios is a library for http communication, making ajax requests, and so on. There is also a library called ‘vue-resource’ to do such things, but it’s said that it is not used well due to it’s slow update cycle and larger community of Axios.
Install Axios
Enter the following command line to install Axios.
npm install --save axios
Then add method in main.js so that Axios can be used globally.
import Vue from 'vue' | |
import App from './App' | |
import axios from 'axios' | |
Vue.prototype.$http = axios | |
app = new Vue({ | |
el: '#app', | |
components: { App }, | |
template: '<App/>' | |
}) |
Using Axios
Using a service called JSONPlaceholder, I’ll test the Axios I just installed. You can copy and paste following code.
<template lang="pug"> | |
div#app | |
div( | |
v-for="user in users" | |
:key="users.id" | |
) | |
h1 {{ user.name }} | |
p {{ user.email }} | |
button(@click="fetchUsers") Click me! | |
</template> | |
<script> | |
export default { | |
name: 'app', | |
data () { | |
return { | |
users: [] | |
} | |
}, | |
methods: { | |
fetchUsers: function () { | |
const baseURI = 'https://jsonplaceholder.typicode.com/users' | |
this.$http.get(baseURI) | |
.then((result) => { | |
this.users = result.data | |
}) | |
} | |
} | |
} | |
</script> | |
<style lang="scss"> | |
#app { | |
font-family: 'Avenir', Helvetica, Arial, sans-serif; | |
-webkit-font-smoothing: antialiased; | |
-moz-osx-font-smoothing: grayscale; | |
text-align: left; | |
width: 640px; | |
margin: 0 auto; | |
color: #2c3e50; | |
margin-top: 60px; | |
} | |
</style> |
Internet Explorer
Basically, IE doesn’t support promise, so you may need polyfill of es6-promise to enable it. You can install it with command below.
npm install --save es6-promise
Next, just add one line below in your webpack config file.
require('es6-promise').polyfill(); |
Takeaway
Hope you enjoyed my short tutorial about Vue.js + Axios. Please feel free to contact me — visit my LinkedIn, or just send me an Email to ghsspower@gmail.com. Thanks!
Title : Using Axios in Vue.js
Date : August 5, 2018
Writer : Hyouk Seo (Spemer)