Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve config and env variable in vue component

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 ?

like image 550
Komarzer Avatar asked Feb 14 '18 11:02

Komarzer


2 Answers

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 8.x, in case you want to have a look.

like image 57
Andre W. Avatar answered Oct 19 '22 03:10

Andre W.


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.

like image 36
agm1984 Avatar answered Oct 19 '22 04:10

agm1984