Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import Axios Method Globally in Vuejs

this is my ~/plugins/axios.js file:

import axios from 'axios'

let api = axios.create({
  baseURL: 'http://localhost:8000/api/v1/'
})

export default api

When I want to use axios in every components, I must have write this line:

import api from '~/plugins/axios

How can i config it globally, just write $api instead?

like image 481
KitKit Avatar asked May 16 '18 12:05

KitKit


People also ask

Can I install Axios globally?

P.A They can be anywhere you want. If you didn't want to clutter main. js just put the statements into a lib/axios. js file or something and add all your interceptors, and then export the axios object, and you can assign it in main.


2 Answers

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://vuejs.org/v2/guide/plugins.html

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

like image 197
Frondor Avatar answered Oct 04 '22 23:10

Frondor


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.

like image 33
Viral Patel Avatar answered Oct 05 '22 00:10

Viral Patel