2

I added Axios to my Vue app via Vue UI dependency installation. I would like to access Axios within my components by using

this.$http.myHTTPmethod

So I created http.js based on this documentation

https://github.com/axios/axios#axioscreateconfig

import axios from "axios";

const devInstance = createInstance("http://localhost:3000");
const productionInstance = createInstance("http://localhost:3000"); // will change later

function createInstance(baseURL){
    return axios.create({
        baseURL,
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${localStorage.token}`
        }
    });
}

export default devInstance; // Check debug/build mode

My question:

How can I make axios use this axios instance? And how can I access this instance via this.$http like I would do with the Vue-Router (this.$router)?

1 Answer 1

10

You could make a plugin:

import axios from "axios";
import Vue from 'vue'

const devInstance = createInstance("http://localhost:3000");
const productionInstance = createInstance("http://localhost:3000"); // will change later

function createInstance(baseURL){
    return axios.create({
        baseURL,
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${localStorage.token}`
        }
    });
}

export default {
    install () {
        Vue.prototype.$http = devInstance
    }
}; // Check debug/build mode

And then your plugin into your main.js file, before creating your main Vue instance just like this:

import Vue from 'vue'
import http from './plugins/http.js'

Vue.use(http)
...

By doing this, you will have access to your axios instance from your components using this.$http

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.