I'm setting up some Vue Components in my Laravel 5.8 application, that require user information available through Auth::user()
, most importantly, the api_token
that I must use in my axios requests. I want to pass the Auth::user()
object from Laravel to Vue in a secure and private method.
I initially passed the object as props, but I don't want private information on the object to be easily exposed using browser extensions such as Vue DevTools. Now, I've been searching for a way to define global variables inside the Blade Template and access them in Vue:
Pass data from blade to vue component
https://forum.vuejs.org/t/accessing-global-variables-from-single-file-vue-component/638
https://zaengle.com/blog/layers-of-a-laravel-vue-application
Based on those links above, it seems like what I need to do is set the variables to the window object, but I'm unsure on what I'm doing something wrong to achieve this. When I define the variable in the Blade Template, I can see the variable is assigning properly by doing console.log()
but the problem comes when I try to use it in Vue.
app.blade.php
@if(Auth::user())
<script>
window.User = {!! json_encode(Auth::user()) !!}
console.log(window.User)
</script>
@endif
component.vue
<script>
export default {
data: function() {
return {
user: window.User
}
}
}
</script>
I've tried setting the data as window.User
, this.User
, and simply just User
but it always comes up as undefined
. What am I missing? Or is there any other/better way to do this?
console.log(window.User)
and the console print the user data normally. – Philnpm run dev
, on production you have to go withnpm run build
or something similar, maybenpm run prod
– Tarasovychuser: window.User
it says it's undefined. – AndrykVP