Vue.js 创建全局Axios配置并将其添加到Vue实例

Vue.js 创建全局Axios配置并将其添加到Vue实例,vue.js,axios,Vue.js,Axios,我通过Vue UI依赖项安装将Axios添加到我的Vue应用程序中。我想通过使用访问组件中的Axios this.$http.myHTTPmethod 因此,我基于此文档创建了http.js 我的问题: 如何使axios使用此axios实例?我如何像使用Vue路由器一样通过this.$http访问此实例(this.$Router)?您可以制作一个插件: import axios from "axios"; import Vue from 'vue' const devInstance = c

我通过Vue UI依赖项安装将Axios添加到我的Vue应用程序中。我想通过使用访问组件中的Axios

this.$http.myHTTPmethod

因此,我基于此文档创建了http.js

我的问题:


如何使axios使用此axios实例?我如何像使用Vue路由器一样通过
this.$http
访问此实例(
this.$Router
)?

您可以制作一个插件:

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
然后将插件插入到
main.js
文件中,然后再创建主Vue实例,如下所示:

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

Vue.use(http)
...

这样,您就可以使用
this从组件访问
axios
实例。$http
您可以制作一个插件:

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
然后将插件插入到
main.js
文件中,然后再创建主Vue实例,如下所示:

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

Vue.use(http)
...
这样,您就可以使用
this从组件访问
axios
实例。$http