在Vue中创建axios实例不起作用

PJC*_*der 2 javascript vue.js axios

我在Vue中将axios用于AJAX。在You撰写的文章中,他提到我们可以设置Vue.prototype.$http = axios并且我可以this.$http在Vue实例中使用。工作正常。

但是,如果我想为创建axios实例$http,例如

Vue.prototype.$http = axios.create({
  baseURL: 'https://app.herokuapp.com/'
})
Run Code Online (Sandbox Code Playgroud)

我使用时不起作用this.$http.get('/relativeURL')。看来它无法访问我设置的配置。也就是说,它不会将请求发送到https://app.herokuapp.com/relativeURL

换句话说,如果我在其他任何对象(例如)中设置axios实例Vue.prototype.$axios = axios.create({config})。它可以成功工作。

有人可以解释为什么会这样吗?

Sau*_*abh 5

虽然在Vue实例级别定义它可能有其自身的优点,但我不喜欢污染全局名称空间。我的方法是,有一个gateway文件夹,其中有axios实例的不同文件,例如:

backend-api.js

import axios from 'axios'
export default axios.create({
  baseURL: 'http://YourAPiIp:9090/api/v1',
  timeout: 100000,
  headers: {
    'Content-Type': 'application/json'
  }
})
Run Code Online (Sandbox Code Playgroud)

现在,您可以将其导入所需的位置并使用它:

import backendApi from '../../gateways/backend-api'
Run Code Online (Sandbox Code Playgroud)