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 ?
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With