访问模板中的vue环境变量

2023-12-24

我想从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="" />

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


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

事物是可以定义的globally https://v3.vuejs.org/api/application-config.html#globalproperties对于所有组件,例如对于 Vue 2:

Vue.prototype.$baseUrl = process.env.VUE_APP_API_BASE_URL;

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

访问模板中的vue环境变量 的相关文章

随机推荐