Nuxt3 - Pinia 商店中无法访问环境变量

Wal*_*riq 3 javascript runtime-error vue.js nuxtjs3

我有一个问题。我实际上正在尝试BASE_URL通过 nuxt 从 Pinia 商店中的 env进行访问runtimeConfig,它给出了错误500 nuxt 实例不可用

这是错误图像

在此输入图像描述

我想指出的一件事是,当我硬编码时BASE_URL它工作正常,但是当我尝试从环境变量访问时BASE_URL它会出现错误。

这是我的代码

皮尼亚店

// Pinia Store for Home Page
import { useRuntimeConfig } from '#app'

const BASE_URL = useRuntimeConfig().public.api_url

export const useHomeStore = defineStore('home-store', {
  state: () => ({
    homePageData: {}
  }),

  actions: {
    async getHomePageData() {
      this.homePageData = await $fetch(`${BASE_URL}/products`)
    }
  }
})
Run Code Online (Sandbox Code Playgroud)

努克斯配置

// https://v3.nuxtjs.org/api/configuration/nuxt.config
export default defineNuxtConfig({
  runtimeConfig: {
    public: {
      api_url: process.env.BASE_URL
    }
  }
})
Run Code Online (Sandbox Code Playgroud)

小智 8

好吧,看来我明白这个问题了。

主要问题是您无法useRuntimeConfig从商店外部访问该功能。

这个例子:

home-store.ts

/**
 * BAD - outside store, not working
 */
const BASE_URL = useRuntimeConfig().public.api_url;

export const useHomeStore = defineStore('home-store', {
  state: () => ({
    homePageData: {},
  }),

  actions: {
    async getHomePageData() {
      /**
       * GOOD - inside store
       */
      const BASE_URL = useRuntimeConfig().public.api_url;
      console.log('BASE_URL HERE:', BASE_URL);
      this.homePageData = await $fetch(`${BASE_URL}/products`);
    },
  },
});
Run Code Online (Sandbox Code Playgroud)