Retrieve config and env variable in vue component
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
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.