Vue3组合式API中Axios配置问题:baseURL未生效
一、请求未使用baseURL的原因及解决方法
你的请求指向Vue应用的localhost:3000而非配置的https://localhost:7281,核心原因有两个:
组件导入错误
你在组件里写的是import api from 'axios',这导入的是官方原始的Axios包,不是你在plugins/axios.ts里配置好的带baseURL的api实例,所以自然用的是Axios默认配置,没有baseURL。Axios实例注册方式错误
在plugins/index.ts里,你用app.use(api)尝试注册Axios,但Axios实例本身并不是Vue插件,use方法只接受符合Vue插件规范的对象(带有install方法),所以这行代码根本没起到把你的api实例挂载到全局的作用。
解决步骤:
方法1:直接导入配置好的api实例(推荐,更符合模块化)
修改组件中的导入语句,指向你自己的配置文件:
<script setup lang="ts"> import { ref } from 'vue' // 注意路径要根据你的项目结构调整,@通常指向src目录 import api from '@/plugins/axios' api.get('/Account', { timeout: 5000 }) .then(response => { console.log(response) }) </script>
方法2:挂载到Vue全局属性(适合全局频繁使用的场景)
如果想在所有组件里不用导入直接通过$axios使用,需要修改plugins/axios.ts,给实例添加install方法,让它成为Vue插件:
// plugins/axios.ts import axios, { AxiosInstance } from 'axios'; declare module '@vue/runtime-core' { interface ComponentCustomProperties { $axios: AxiosInstance; } } const api = axios.create({ baseURL: 'https://localhost:7281', headers: { 'Content-type': 'application/json' }, }); // 添加install方法,让Axios实例成为Vue插件 api.install = (app: any) => { app.config.globalProperties.$axios = api; }; export default api
然后在组件中就可以这样使用(<script setup>中需要用getCurrentInstance获取全局属性):
<script setup lang="ts"> import { ref, getCurrentInstance } from 'vue' const { proxy } = getCurrentInstance()!; proxy?.$axios.get('/Account', { timeout: 5000 }) .then(response => { console.log(response) }) </script>
二、declare module代码的作用
这段代码是TypeScript的类型扩展:
declare module '@vue/runtime-core' { interface ComponentCustomProperties { $axios: AxiosInstance; } }
因为Vue 3的TypeScript类型系统默认不知道你给组件全局属性添加了$axios,如果没有这段代码,当你在组件里使用this.$axios或者通过proxy.$axios调用时,TypeScript会报错,提示找不到$axios这个属性。
这段代码的作用就是告诉TypeScript:Vue组件的自定义属性集合里,新增一个类型为AxiosInstance的$axios属性,这样在编写代码时就能获得正确的类型提示和语法检查,避免类型错误。
内容的提问来源于stack exchange,提问作者Qiuzman

