You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pinia Store中使用Vue.js的全局Axios实例?

在Vue 3的Pinia Store中使用全局Axios实例的解决方案

问题说明

你在Vue 3项目中通过app.config.globalProperties挂载了自定义的Axios实例$http,Vue组件中可以正常调用,但在Pinia Store里访问this.$http时返回undefined,包括$route这类全局属性也无法在Store中直接使用。

原因

Pinia的Store实例与Vue组件实例是完全独立的,app.config.globalProperties仅会将属性挂载到Vue组件实例上,所以Store无法直接获取到这些全局属性。

解决方法

方法一:直接导入Axios实例(推荐)

把Axios实例抽成独立模块,在组件和Store中统一导入使用,这种方式更清晰也更符合模块化开发思路:

  1. 创建独立的Axios实例文件
    在src/utils/axios.js中定义并导出Axios实例:
import axios from 'axios';

export const axiosInstance = axios.create({
    baseURL: "http://localhost:8000/",
    headers: {
        "Content-Type": "application/json"
    }
});
  1. 在main.js中挂载全局(保留组件的使用方式)
import { createApp } from 'vue';
import App from './App.vue';
import { axiosInstance } from './utils/axios';
import { createPinia } from 'pinia';

const app = createApp(App);
// 挂载到组件全局属性,兼容原有组件写法
app.config.globalProperties.$http = axiosInstance;

const pinia = createPinia();
app.use(pinia);

app.mount('#app');
  1. 在Pinia Store中导入使用
import { defineStore } from 'pinia';
import { axiosInstance } from '@/utils/axios';

export const useDateStore = defineStore("dateStore", {
    state: () => ({
        allowedDates: []
    }),
    actions: {
        async fetchAvailableDates() {
            const response = await axiosInstance.get("get-dates");
            this.allowedDates = response.data;
        }
    }
});

方法二:通过Pinia插件注入全局属性

如果希望在所有Store中能直接通过this.$http访问Axios实例,可以编写Pinia插件实现注入:

  1. 在main.js中配置Pinia插件
import { createApp } from 'vue';
import App from './App.vue';
import { axiosInstance } from './utils/axios';
import { createPinia } from 'pinia';
// 如果需要注入$route,需导入useRoute
// import { useRoute } from 'vue-router';

const pinia = createPinia();
// 添加插件注入Axios实例
pinia.use(({ store }) => {
    store.$http = axiosInstance;
    // 若需注入路由,取消下方注释
    // store.$route = useRoute();
});

const app = createApp(App);
app.use(pinia);
// 保留组件全局挂载(可选)
app.config.globalProperties.$http = axiosInstance;

app.mount('#app');
  1. 在Store中直接使用this.$http
import { defineStore } from 'pinia';

export const useDateStore = defineStore("dateStore", {
    state: () => ({
        allowedDates: []
    }),
    actions: {
        async fetchAvailableDates() {
            const response = await this.$http.get("get-dates");
            this.allowedDates = response.data;
        }
    }
});

内容的提问来源于stack exchange,提问作者Philip

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 18:05:24