简体   繁体   English

如何从 Astro 中的框架组件访问环境变量?

[英]How access environment variables from a Framework Components in Astro?

I'm working in a project using Astro and I am using a component with VUE.我在一个使用 Astro 的项目中工作,我正在使用一个带有 VUE 的组件。 For this project I need to access some env vars.对于这个项目,我需要访问一些环境变量。

I am able to access from the Astro templates, but I can't find a way to get in the VUE component.我可以从 Astro 模板访问,但我找不到进入 VUE 组件的方法。 Is this possible?这可能吗?

There is no way to do this without exposing the environment variables.如果不暴露环境变量,就无法做到这一点。

To do this, we have to move the function to an endpoint of our API that runs on the server side and make a request to execute it safely.为此,我们必须将 function 移动到在服务器端运行的 API 的端点,并发出请求以安全地执行它。

You can expose the env var as data to the Vue component like so...您可以像这样将 env var 作为数据公开给 Vue 组件......

Vue 2
<script>
const { PUBLIC_ENV_HERE } = import.meta.env;

export default {
  data() {
    return {
      PUBLIC_ENV_HERE,
    };
  },
};
</script>

Vue 3 with script setup
<script setup>
const { PUBLIC_ENV_HERE } = import.meta.env;
</script>

Remember to prefix client side variables with PUBLIC - see https://docs.astro.build/en/guides/environment-variables/ for more info.请记住在客户端变量前加上PUBLIC - 请参阅https://docs.astro.build/en/guides/environment-variables/了解更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM