Maxiss
Maxiss

Reputation: 1056

Laravel + Vue.js - how to have a global variable?

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');
});

Upvotes: 2

Views: 5193

Answers (1)

Hafez Divandari
Hafez Divandari

Reputation: 9069

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>

Upvotes: 5

Related Questions