Import Axios Method Globally in Vuejs

You can create a plugin and use it like this in your main.js file (if you're using something like vue-cli)

import axios from 'axios'

Vue.use({
    install (Vue) {
    Vue.prototype.$api = axios.create({
      baseURL: 'http://localhost:8000/api/'
    })
  }
})

new Vue({
    // your app here
})

Now, you can do this.$api.get(...) on every component method

Read more about Vue plugins here: https://v2.vuejs.org/v2/guide/plugins.html

Provide/Inject could be an option as well: https://v2.vuejs.org/v2/api/#provide-inject


There is a window object available to you in the browser. You can actively leverage that based on your requirements.

In the main.js file

import axiosApi from 'axios';

const axios = axiosApi.create({
    baseURL:`your_base_url`,
    headers:{ header:value }
});

//Use the window object to make it available globally.
window.axios = axios;

Now in your component.vue

methods:{
    someMethod(){
        axios.get('/endpoint').then(res => {}).catch(err => {});
    }
}

This is basically how I use axios globally in my projects. Also, this is also how Laravel uses it.