无法访问组件 nuxt 中的 process.env 变量 [英] Can not access process.env variables in component nuxt

查看:110
本文介绍了无法访问组件 nuxt 中的 process.env 变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 nuxt 配置中我有 env 对象

In nuxt config I have env object

env: {
    hey: process.env.hey || 'hey'
},

只要我想在组件模板中显示它:

as soon as I want to display it in component template:

{{ process.env.hey }}

我有一个错误

无法读取未定义的属性env"

Cannot read property 'env' of undefined

知道是什么原因造成的吗?

Any idea what can cause that?

推荐答案

Nuxt <2.13

process 不能直接用于模板,但您可以通过创建计算属性或将其添加到组件的状态来访问它.举个例子:

process isn't directly available to templates, but you can access it by creating a computed property or adding it to your component's state. Here's an example:

<template>
  <div>{{ message }}</div>
</template>

export default {
  computed: {
    message() {
      return process.env.hey;
    },
  },
};

Nuxt >= 2.13

您现在可以使用 运行时配置,例如所以:

You can now use the runtime config like so:

nuxt.config

export default {
  publicRuntimeConfig: {
    message: process.env.hey || 'hello world!',
  },
};

template.vue

<template>
  <div>{{ $config.message }}</div>
</template>

这篇关于无法访问组件 nuxt 中的 process.env 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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