如何将 $axios 注入 Pinia store SSR

How to inject $axios into Pinia store SSR

我正在尝试将我的 axios 实例注入商店,以便我能够登录应用程序,但不幸的是我无法登录。我有以下引导文件

import { boot } from 'quasar/wrappers';
import axios from 'axios';
import type {AxiosResponse} from 'axios';
import type { StatusCodes } from 'http-status-codes';

export type WrappedResponse = { response?: AxiosResponse };

export const isError = (e: WrappedResponse, statusCode: StatusCodes) =>
  e.response && e.response.status === statusCode;

export default boot(({ app, store }) => {
  const api = axios.create({ baseURL: import.meta.env.VITE_APP_API_BASE_URL });

  app.provide('axios', api);
  store.$axios = api;
});

那么在我的店里我有:

import { defineStore } from 'pinia';

export const useAppStore = defineStore('app', {
  state: () => ({
  }),
  getters: {
  },
  actions: {
    async login() {
      console.log(this.$axios);
      console.log('Logging in from store');
    }
  },
});

每当调用 login 时,它都会打印 undefined。知道我做错了什么吗?

您只需创建一个 Pinia plugin:

export default boot(({ app, store }) => {
  const api = axios.create({ baseURL: import.meta.env.VITE_APP_API_BASE_URL });

  app.provide('axios', api);
  store.use(() => ({ api })); // 
});