Search code examples
javascriptlaravelglobal-variablesvue.jsvuejs2

Vus.js 2.0 Laravel 5.4 pass object to app and use it globally accross components


I want to load the authenticated user and use it accross all my vue components (without an unnecessary ajax request since I can load it directly from the back-end).

My Laravel home.blade.php references a Vue app and I tried binding the Auth::user() to the main vue:

<div id="app" :authuser="{{ Auth::user() ? : '[]' }}"></div>

My app.js file looks like this:

const app = new Vue({
  el: '#app',
  props: ['authuser'],
  data: { authuser: this.authuser }
});

But it seems you cannot pass props to the main Vue object. What is the best way to do it?

Note: I am open to other suggestions than passing through props. Ideally, I would like to reference an authuser object globally from all my vue components. Maybe through window.authuser for example?


Solution

  • Adding this to the blade template before calling app.js does the trick:

    <script>
      let authuser = {!! Auth::user() ? : '[]' !!};
    </script>
    <script src="{{asset('js/app.js') }}"></script>
    

    This will allow you to use authuser directly and globally in any component, for example:

    <template>
      <div class="answer" v-if="authUserAnswered">
         Edit Answer
      </div>
    </template>
    
    <script>
      export default {
        props: ['answer'],
        computed: {
          authUserAnswered() { return authuser.id == this.answer.user_id; }
        }
      }
    </script>
    

    This is cleaner than using this.$root every time.

    You can learn more about Shared States here.