Iqbal Hossain
Iqbal Hossain

Reputation: 23

Vue.js: Axios is not working in Vue when calling an API

Here is my code:

Main.js

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

Vue.config.productionTip = false
var eventBus = new Vue();
Vue.prototype.$eventBus = eventBus;
Vue.prototype.$axios = axios;

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

Calling API

methods:{
    loginMethode(){
        console.log(this.user);
        this.$eventBus.$emit("loadingStatus",true);
        this.$axios.get('https://api.coindesk.com/v1/bpi/currentprice.json')
        .then(res=>{
            console.log(res);
        });
        this.$eventBus.$emit("loadingStatus",false);
    }
  }

It's showing an error message that

Error in v-on handler: "TypeError: Cannot read property 'get' of undefined"

Upvotes: 0

Views: 1613

Answers (1)

Maxim Dyuzhinov
Maxim Dyuzhinov

Reputation: 308

You see the error, because "$axios" object that you define inside a Main.js module is not defined inside your ./App.js module. You should pass it there somehow. Consider to use vue mixins or component extention or composition API.

Upvotes: 1

Related Questions