Vue 3 - 全局 axios 实例

Vue 3 - global axios instance

我想在我的 Vue 3 应用程序中创建一个全局可用的 axios 实例。

设置:

import { createApp } from 'vue'
import axios from 'axios'

const axiosInstance = axios.create({
  withCredentials: true,
})

const app = createApp()

app.config.globalProperties.$axios = axiosInstance

app.mount(el)

用法:

let response = await this.$axios.get('/api/leads')

我收到这个错误:

TypeError: this.$axios.get is not a function

似乎 this.$axiosundefined。我不知道为什么。

备注:

  1. 我正在使用 Vue 的 @vue/compat 版本从 Vue 2 迁移到 Vue 3。我正在关注 official migration guide
  2. 检查 this.$axios 时 - 我得到 ƒ wrap() ......

问题是known bug, where function properties (the result of axios.create() is actually a function) are bound to the component instance proxy, which inadvertently hides the function's own attached properties (i.e., $axios.get in this case). The PR that fixes the issue还没有被合并

一种解决方法是将 axiosInstance(一个函数)转换为一个带有扩展运算符的对象:

const axiosInstance = axios.create({
  withCredentials: true,
})

const app = createApp()
                                        
app.config.globalProperties.$axios = { ...axiosInstance }

demo