【问题标题】:Creating an instance of axios in Vue not working在 Vue 中创建 axios 实例不起作用
【发布时间】:2017-09-10 12:13:31
【问题描述】:

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

但是,如果我想创建一个axios实例到$http,就像

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

当我使用this.$http.get('/relativeURL') 时它不起作用。它似乎无法访问我设置的配置。即不会向https://app.herokuapp.com/relativeURL发送请求

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

有人能解释一下为什么会这样吗??

【问题讨论】:

    标签: javascript vue.js axios


    【解决方案1】:

    你设置

    Vue.prototype.$https = axios.create({
      baseURL: 'https://app.herokuapp.com/'
    })
    

    并使用

    this.$http...
    

    属性名称中的错字(https 与 http)。

    保留为 $http。或者,如果 $http 误导了您,甚至根本不声明它 - 仅使用 this.axios.get...

    【讨论】:

    • 抱歉,打错了。
    【解决方案2】:

    虽然在 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'
      }
    })
    

    现在您可以将其导入您想要的地方并使用它:

    import backendApi from '../../gateways/backend-api'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-18
      • 1970-01-01
      相关资源
      最近更新 更多