在模板中访问 vue 环境变量 [英] access vue environment variables in template

查看:127
本文介绍了在模板中访问 vue 环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to access my environment variables from the template of vue single file components however, doing the following:

<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

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

i know my environment variables are set up correctly as i can use them in other places, and i can use a workaround to create a new variable on the component and reference that:

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

<img :src="`${BaseUrl}/image/${image.filename}`" alt="" />

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

and that is able to load the image correctly, but how can i access the env variables directly in the template without the need to initialise a new variable for each component?

推荐答案

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

process.env environment variables are replaced with actual values at compilation time. The error means that this doesn't happen in templates.

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

Things can be defined globally for all components, e.g. for Vue 2:

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

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

Putting too much code into templates is a bad practice. In this case image URL can be defined as computed, or as method for image provided by v-for.

这篇关于在模板中访问 vue 环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆