Using Axios in Vue.js

A Vue.js + Axios tutorial for beginners


Vue.js logo

Axios is a library for HTTP communication, AJAX requests, and so on. There's also vue-resource, but it's said to be less commonly used because of its slower update cycle and the larger community around Axios.

Install Axios

Run the following command to install Axios:

npm install --save axios

Then add a method in main.js so Axios is available 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 install. Copy and paste the snippet below.

<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

IE doesn't support promises, so you may need an es6-promise polyfill to enable them. Install it with:

npm install --save es6-promise

Then add the line below to your webpack config:

require('es6-promise').polyfill();

Takeaway

I hope you enjoyed this short Vue.js + Axios tutorial. Feel free to reach out via LinkedIn or by email at ghsspower@gmail.com. Thanks!

Title : Using Axios in Vue.js
Date : August 5, 2018
Writer : Hyouk Seo (Spemer)