【发布时间】:2021-07-31 06:15:52
【问题描述】:
我想从vue单文件组件的模板中访问我的环境变量 但是,请执行以下操作:
<img :src="`${process.env.VUE_APP_API_BASE_URL}/image/${image.filename}`" alt="" />
给我错误:
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
我知道我的环境变量设置正确,因为我可以在其他地方使用它们,并且我可以使用解决方法在组件上创建一个新变量并引用它:
data() {
return {
BaseUrl: process.env.VUE_APP_API_BASE_URL,
};
},
<img :src="`${BaseUrl}/image/${image.filename}`" alt="" />
并且能够正确加载图像,但是我如何直接在模板中访问 env 变量而不需要为每个组件初始化一个新变量?
【问题讨论】:
-
您是否使用 Nuxt.js 进行服务器端渲染?
-
那是因为 process 是全局的,但是在模板中使用了本地变量(就像在它们之前有 this.),所以你可以定义计算 prop,例如 $process: process,所以它可以被使用在模板占位符中。
-
@TJ 不,这是水疗中心
-
@willystyle 有没有办法自动将它加载到所有组件中?所以我不必单独定义它?
标签: html vue.js templates environment-variables