在vue组件中检索config和env变量 [英] Retrieve config and env variable in vue component

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

问题描述

我的Laravel应用程序中有一个Vue组件.

I have a Vue component in my Laravel application.

我想直接在Vue组件中检索配置(或.env Laravel文件)中的URL,而不是对其进行硬编码. 在webpack laravel mix中,我可以像这样检索我的.env变量.

I want to retrieve a URL that is in a config (or the .env Laravel file) directly in my Vue component, instead of hardcoding it. In webpack laravel mix I can retrieve my .env variable like this.

require('dotenv').config() let proxyUrl = process.env.APP_URL

require('dotenv').config() let proxyUrl = process.env.APP_URL

但是当我想在我的app.js中执行此操作时,在尝试要求dotenv时出现了can't resolve fs.

But when I want to do this in my app.js, I have a can't resolve fs when trying to require dotenv.

在我的Vue组件中提供这些数据的最佳方法是什么?

What is the best way to have this data available in my Vue components ?

推荐答案

我也遇到了同样的问题,但是将变量放置在Blade中对我来说不是一个选择,这还意味着在Blade文件中声明一个变量,然后使用在一个看起来有点杂乱无章的javascript文件中.因此,如果您处于同一位置,那么我认为有一个更好的解决方案.如果您使用的是Vue,则很可能是使用Laravel mix来编译文件的.

I had this same issue, but placing the variable in blade was not an options for me, also it meant having a variable declare in a blade file and then use in a javascript file which seems a bit unorganized. So if you are in this same position then I think there is a better solution. If you are using Vue you most likely are compiling your files using Laravel mix.

如果是这种情况,您可以将环境变量注入Mix中,则只需添加前缀MIX_.因此,您可以在.env文件中添加一个变量,例如:

If this is the case you can inject environment variables into Mix, you just need to add the prefix MIX_. So you can add to your .env file a variable like:

MIX_SENTRY_DSN_PUBLIC=http://example.com

,然后在您的javascript文件中访问此变量,如下所示:

and then access this variable like this in your javascript file:

process.env.MIX_SENTRY_DSN_PUBLIC

您可以在预编译文件中的任何位置访问此文件.您可以在laravel文档中找到此信息. https://laravel.com/docs/5.6/mix#environment-variables

you can access this anywhere in your pre compile file. You can find this information in the laravel documentation. https://laravel.com/docs/5.6/mix#environment-variables

这篇关于在vue组件中检索config和env变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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