[英]How to access env variable in functional component?
I would like to define a default value if a prop is not passed to my functional component.如果 prop 没有传递给我的功能组件,我想定义一个默认值。 This default value is an environement variable.
这个默认值是一个环境变量。
When I try the following, compilation will throw an error TypeError: Cannot read property 'env' of undefined
当我尝试以下操作时,编译会抛出错误
TypeError: Cannot read property 'env' of undefined
<template functional>
<div class="header__small">{{ props.header_small ? props.header_small : process.env.VUE_APP_DEFAULTHEADER }}</div>
</template>
The same happens if I try with parent.process.env.VUE_APP_DEFAULTHEADER
如果我尝试使用
parent.process.env.VUE_APP_DEFAULTHEADER
也会发生同样的情况
The env variable are working fine in every other classic component accross the app. env 变量在应用程序中的所有其他经典组件中都可以正常工作。 It just won't work with functional ones.
它只是不适用于功能性的。 Ternary operator to define a default value works well also if I pass it any other value, just not process.env.
如果我将任何其他值传递给它,而不是 process.env,那么定义默认值的三元运算符也能很好地工作。
As you are using it only as default value for a prop, did you try this?由于您仅将其用作道具的默认值,因此您尝试过吗?
props: {
header_small: {
type: String,
default: process.env.VUE_APP_DEFAULTHEADER
}
}
process.env.XXX
cannot be used in template directly - applies to statefull and functional components alike process.env.XXX
不能直接在模板中使用 - 适用于有状态和功能组件<script>
part of the component<script>
部分default
value of prop
declaration or directly in render()
function codeprop
声明的default
值或直接在render()
函数代码中才能使用的地方In Webpack/Vue CLI projects, environment variables are handled by Webpack DefinePlugin .在 Webpack/Vue CLI 项目中,环境变量由 Webpack DefinePlugin处理。 It replaces any occurrence of
process.env.XXX
by some string value defined in .env
files.它用
.env
文件中定义的一些字符串值替换任何出现的process.env.XXX
。 This happens at build time.这发生在构建时。
For some reason it works only when used inside <script>
part of SFC's (JS most of the time).出于某种原因,它仅在 SFC 的
<script>
部分(大部分时间是 JS)中使用时才有效。 But we know that Vue templates are compiled into plain JavaScript too.但是我们知道 Vue 模板也被编译成纯 JavaScript 。 So why is it it doesn't work also in the template ?
那么为什么它在模板中也不起作用呢? I was trying to google a bit but didn't found any answer.
我试图用谷歌搜索一下,但没有找到任何答案。 So I guess it was a decision of
vue-loader
creators to not allow DefinePlugin to process the output of the Vue compiler maybe because its nature (essentially string replacement) and fear of hard to debug/support issues...所以我想这是
vue-loader
创建者的一个决定,不允许 DefinePlugin 处理 Vue 编译器的输出,这可能是因为它的性质(本质上是字符串替换)以及对难以调试/支持问题的恐惧......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.