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

2👍

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.

0👍

One way to do this can be using $root. As suggested here, you should be able to set in the app component and use it across components.

In your app.js:

const app = new Vue({
  el: '#app',
  created () {
    // will fire the first time the router is loaded,
    // and won't be called again until page refresh
    // maybe load in your data dynamically?
    this.$root.authuser = this.authuser;
  }
});

And then in your component:

this.$root.authuser

Other way to do this can be using a central state or vuex which is more popular among the community. You can have a look at similar answer here. You can commit to vuex mutation in the created/mounted block of app.js and later can access it in any components with help of getters.

0👍

In app.js, you can declare global variables.

For example:

// app.js
global.user = 'hello';

// anywhere else, you can access the user var
console.log(user);

You can also apply this to the vue object itself(if you want):

global.vm = new Vue({
    methods: {
        helloWorld(){}
    }
});

And you’ll be able to access it’s methods and so on from other components: vm.helloWorld();.

To get user into app.js, you may print it in JSON between script tags. Your app.js should be able to access it later. eg.

<script>
    var user="{{$user}}";
</script>
<script src="app.js" type="text/javascript"></script>

But maybe it would be better to use an AJAX request.

👤JC Lee

Leave a comment