Getting data from API in VueJs with Axios

To work with the Vuejs front-end framework the most common thing is to interact with API, one of the ways to call API we can use Axios. This article will show you the simplest ways to consume API with Axios in your VueJs application.

Here is the sample code for how to use Axios

Installing Axios dependency

Go to your project terminal type

npm install axios

Register Axios to your Vue application

In your /src/main.js

import Vue from 'vue'
import App from './App.vue'
import router from './routes'
import axios from 'axios'

Vue.prototype.$axios = axios
Vue.config.productionTip = false

new Vue({
    router,
    render: h => h(App)
}).$mount('#app')

Calling API with Axios

After registering Axios to Vue.prototype.$axios you can call Axios by this.$axios

<template>
    <div>
        <h5>Currency Rate</h5>
        <div v-for="(currency, index) in currency_rate" :key="index">
            <span>{{ currency.code }} - </span><span>{{ currency.rate }}</span>
        </div>
    </div>
</template>

<script>
export default {
    data() {
        return {
            currency_rate: {}
        }
    },
    mounted() {
        this.$axios.get('https://api.coindesk.com/v1/bpi/currentprice.json')
            .then(res => {
                this.currency_rate = res.data.bpi
            });
    }
}
</script>