访问模板中的vue环境变量

aid*_*rne 9 html templates environment-variables vue.js

但是,我想从 vue 单文件组件的模板访问我的环境变量,请执行以下操作:

<img :src="`${process.env.VUE_APP_API_BASE_URL}/image/${image.filename}`" alt="" />
Run Code Online (Sandbox Code Playgroud)

给我错误:

 Property or method "process" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property
Run Code Online (Sandbox Code Playgroud)

我知道我的环境变量设置正确,因为我可以在其他地方使用它们,并且我可以使用解决方法在组件上创建一个新变量并引用:

data() {
  return {
    BaseUrl: process.env.VUE_APP_API_BASE_URL,
  };
},

<img :src="`${BaseUrl}/image/${image.filename}`" alt="" />
Run Code Online (Sandbox Code Playgroud)

这能够正确加载图像,但是如何直接在模板中访问环境变量,而不需要为每个组件初始化新变量?

Est*_*ask 7

process.env环境变量在编译时替换为实际值。该错误意味着这不会在模板中发生。

可以为所有组件全局定义事物,例如 Vue 2:

Vue.prototype.$baseUrl = process.env.VUE_APP_API_BASE_URL;
Run Code Online (Sandbox Code Playgroud)

将太多代码放入模板中是一种不好的做法。在这种情况下,图像 URL 可以定义为computedmethodimage提供v-for