Friday, March 10, 2017

Vuejs Global User Object from Laravel API

I have a small Laravel / VueJS app with single file components and it is a single page application. I use vue-stash for central state managment.

Here is my store.js

export default {
    user: {
        name: null
    }
}

And here is my api call from my dashboard.

<script>
    export default {
        mounted() {
            axios.get('/api/getAuthUser')
                    .then(response => {
                        this.$store.user.name = response.data.name;
                    });
        }
    }
</script>

This works fine and it will set the user name in store to the user name i get from my api call.

But if the first visit to my site is not the dashboard then there is no api call and the name is not set in the store. But I need that name at different places in my app.

I don't wont to call my api from every component. Is it possible to call the api only once directly from my store? How can I do that or is there any better solution?

Thanks!



via user3382438

Advertisement