2

I have a project using Laravel and Vue.js. I guess it wasn't the best idea not to separate them, but we learn from our mistakes ;) Here is how it works:

I have been struggling trying to put global variables, such as "current user". Now, I am calling /currentuser through axios each time I need it, or I put it in props, but it drives my crazy... How can I make it global? I am wondering if Vuex could work in my project, as everything is called from Laravel, the routes as well...

I have tried several things in app.js (here are 2 of them, mixed):

var curruser=null;

axios.get('/currmember').then(
    response => {
        curruser=response.data;
    }
);

Vue.mixin({
    methods: {

    },
    data: function() {
        return {
          myvaiable: '', //this doesn't work eather
          get currentUser() {
            if(curruser==null){
                axios.get('/currmember').then(
                    response => {
                        curruser=response.data;
                        return curruser;
                    }
                );
            }
            return curruser;
          }
        }
      }
});}

in TestComponent.vue

<template>
  <div>
    {{currentUser}}
    {{myvariable}} <!-- none of them display anything -->
  </div>
</template>

Here is how things are working (simplify them very much):

app.js

import Vue from 'vue';
window.Vue = require('vue');

var App = Vue.component('app', require('./App.vue').default, {
    name: 'app'
}); 
var shol = Vue.component('test', require('./components/TestComponent.vue').default); 

let lang=localStorage.Lang!=null?localStorage.Lang:'fr';// = document.documentElement.lang.substr(0, 2); 
init();


function init(){

    const app = new Vue({
        el: '#app',
        i18n,
        components:{test
       }
    });

    var curruser=null;

    axios.get('/currmember').then(
        response => {
            curruser=response.data;
        }
    );


    Vue.mixin({
        methods: {

        },
        data: function() {
            return {
                currentUser: 'blabla',
              get currentUser2() {
                if(curruser==null){
                    axios.get('/currmember').then(
                        response => {
                            curruser=response.data;
                            console.log(curruser);
                            return curruser;
                        }
                    );
                }
                return curruser;
              }
            }
          }
    });}

test.blade.php

@extends('template')
@section('pageTitle', 'test' )
@section('contenu')
    <div >
        <test></test>
    </div>

@endsection


web.php
Route::get('/test', function () {
    return view('test');
});

1 Answer 1

5

You may use vuex to access current authenticated user:

On app.js:

import Vue from 'vue';
import store from './store';

const app = new Vue({
    el: '#app',
    store,
    i18n,
    components:{ test },
    created() {
        store.dispatch('getUser');
    }
});

The store.js:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex);

export default new Vuex.Store({
    state: {
        user: {},
    },
    getters: {
        user: state => state.user,
    },
    mutations: {
        setUser(state, user) {
            state.user = user;
        },
    },
    actions: {
        getUser({ commit }) {
            return new Promise((resolve, reject) => {
                axios.get('/currmember')
                    .then(result => {
                        commit('setUser', result.data);
                        resolve();
                    })
                    .catch(error => {
                        reject(error.response && error.response.data.message || 'Error.');
                    });
            });
        },
    }
})

The test component:

<template>
  <div>
    {{ currentUser }}
  </div>
</template>

<script>
export default {
    computed: {
        currentUser() {
           return this.$store.state.user;
        }
    }
};
</script>
Sign up to request clarification or add additional context in comments.

3 Comments

Would you recommend this method to store global settings? What about a mixin or Vue.prototype?
@EugenevanderMerwe Yes it is a standard way to store global settings especially if you want to get/set them or use async actions. I personally use prototype to store global constants / static values.
Thanks @hafez-divandari I'm only working with static values so don't need getters or setters. My biggest challenge is I don't want to make a settings API request on every day. I've also logged this on Laracasts link here if you want to comment as nobody else has.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.