Retrieve config and env variable in vue component

2020-07-10 05:07发布

问题:

I have a Vue component in my Laravel application.

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

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

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

回答1:

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.

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

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

process.env.MIX_SENTRY_DSN_PUBLIC

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



回答2:

To access your env variables in a Vue Component file in Laravel, you will need to prefix your variable with MIX_.

In the .env file

To take your case as an example, if you intend to use APP_URL as a variable in your .env file, instead of APP_URL, you should use MIX_APP_URL like:

MIX_APP_URL=http://example.com

In your Vue Component file

You then access the variable by using the process.env object in your script like:

process.env.MIX_APP_URL

Say today you set a property named proxyUrl and assign the variable as its value, in your script in the .vue file, the code should look like:

export default {
  data () {
        return {
          proxyUrl: process.env.MIX_APP_URL,
        },
  }
}

After that you should be able to retrieve the property in your vue template as normal like:

<template>
    <div>

        //To print the value out
        <p>{{proxyUrl}}</p>

        // To access proxyUrl and bind it to an attribute
        <div :url='proxyUrl'>Example as an attribute</div>
    </div>
</template>

Here is the official doc released in Laravel 6.x, in case you want to have a look.



回答3:

You can do this in Blade template:

let window.something = {{ config('seme_config.something') }}

Then just use the variable in JS with:

window.something

Also, you shouldn't use env() helper directly. Extract data from config file only.



回答4:

IMPORTANT

You have to reload the bundle for the changes to take effect.

Mine didn't work until I killed the dev bundle and re-ran npm run watch.