Skip to main content
Category:

Install axios with npm:

npm install axios --save

 

Example how to import axios in Vue.js:

<script>
import axios from "axios";

export default {
  data() {
    return {};
  },
  mounted() {
    axios.get("https://jsonplaceholder.typicode.com/users")
  }
};
</script>

 

Get and Display Data using Axios in Vue.js:

In this step, we will make the Ajax Request using Axios and show you how to get a response from the server and handle it via Promise Object.

A promise object in JavaScript provides surety for a probable result in future. A promise has 3 presumable states: fulfilled, rejected, or pending.

Example:

<template>
  <div>
    <ul class="test-list" v-for="user in usersList" :key="user.id">
      <li class="test-list--item">
        <strong>{{ user.name }}</strong> <br>
        {{ user.email }} <br>
        {{ user.website }}
      </li>
    </ul>
  </div>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      usersList: []
    };
  },
  mounted() {
    axios.get("https://jsonplaceholder.typicode.com/users")
      .then(res => {
        this.usersList = res.data;
        console.log(this.usersList)
      })
      .catch(error => {
        console.log(error)
         // Manage errors if found any
      })
  }
};
</script>

 

Dealing with Errors:

In an axios call, we’ll do so by using catch() method like this:

 

Example:

<div id="app">
  <h1>Bitcoin Price Index</h1>

  <section v-if="errored">
    <p>We're sorry, we're not able to retrieve this information at the moment, please try back later</p>
  </section>

  <section v-else>
    <div v-if="loading">Loading...</div>

    <div
      v-else
      v-for="currency in info"
      class="currency"
    >
      {{ currency.description }}:
      <span class="lighten">
        <span v-html="currency.symbol"></span>{{ currency.rate_float | currencydecimal }}
      </span>
    </div>

  </section>
</div>

new Vue({
  el: '#app',
  data () {
    return {
      info: null,
      loading: true,
      errored: false
    }
  },
  filters: {
    currencydecimal (value) {
      return value.toFixed(2)
    }
  },
  mounted () {
    axios
      .get('https://api.coindesk.com/v1/bpi/currentprice.json')
      .then(response => {
        this.info = response.data.bpi
      })
      .catch(error => {
        console.log(error)
        this.errored = true
      })
      .finally(() => this.loading = false)
  }
})

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook