[Vuejs]-After laravel-mix upgrade app no longer sees global vars

0👍

Edit 2

Use `window.games, this would "register" your variables globally.


Although, what i do, is the following, consider a MPA not a SPA:

In app.js i just leave the following lines:

require('./bootstrap');

window.Vue = require('vue');

In a separate file, called main.js that i made, i put this, as an example:

import Sidebar from './components/layouts/Sidebar.vue'
import Topnav from './components/layouts/Topnav.vue'

new Vue({
  el: '#sidebar',
  render: h => h(Sidebar)
});

new Vue({
  el: '#topnav',
  render: h => h(Topnav)
});

at the end of app.blade.php i put:

<script src="{{ asset('js/app.js') }}"></script>

<script type="text/javascript">
    const user_props = {
        fullName : {!! json_encode(Auth::user()->fullName) !!},
        username : {!! json_encode(Auth::user()->username) !!},
    }

    user_props.install = function(){
      Object.defineProperty(Vue.prototype, '$userProps', {
        get () { return user_props }
      })
    }

    Vue.use(user_props);
</script>

<script src="{{ asset('js/main.js') }}"></script>

This works because i mount vue in app.js but the components that use user_props are loaded after i declare and install the prototype… Also, since vue is mounted in app.js i can use Vue.use(user_props); after loading it…

And forgot to mention that in webpack.mix.js you should add the main.js:

 mix.js('resources/js/app.js',          'public/js')
    .sass('resources/sass/app.scss',    'public/css')

    .js('resources/js/main.js',        'public/js/')

Edit 1

Based on your comments, and the docs: https://v2.vuejs.org/v2/cookbook/adding-instance-properties.html#The-Importance-of-Scoping-Instance-Properties

The $ is just a convention:

… We scope instance properties with $ to avoid this. You can even use your own convention if you’d like, such as $_appName or ΩappName, to prevent even conflicts with plugins or future features.

So with that in mind you could set it up as:

Vue.prototype.games = games;

then you can access it on every component as this.games

As the documentation implies, when doing this you’ve got to be careful to not overwrite it. So if you have it declared on the data section of your Vue components i think you should delete those lines…

Leave a comment