Francis Kisiara
Francis Kisiara

Reputation: 335

How can I get my Vuex state to initialise within my laravel 5.4 application

I am using Laravel 5.4 and Vuex 2.2.1 for an application. I have a store.js file with the following code.

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

Vue.use(Vuex);

export const store = new Vuex.Store({
    state: {
        testing: 0
    },

    getters: {
        getTest: state => {
            return state.testing + 1;
        }
    }
});

I have a main js file (the one that ships with laravel 5.4),that has the following. I pass the Vuex instance here

require('./bootstrap');;


import VueRouter from 'vue-router';
import { routes } from './routes.js';
import { store } from './libs/store';


Vue.component('fd-auth', require('./components/Auth.vue'));
Vue.component('fd-app', require('./components/App.vue'));



Vue.use(VueRouter);

const router = new VueRouter({
                    routes: routes,
                    mode: 'history'
                });

const app = new Vue({
    el: '#app',
    router: router,
    store
});

I can see the Vuex instance has loaded in my browser.

Vuex Loading

However, when I try to access the data within the store, i get a "Cannot read property of defined" error. It seems my state is still not defined.

I have spent hours on this and just cant wrap my head around it. Could someone help me out and tell me what i am doing wrong.

This is how Im accessing it within a Component.

<script>
import RevealVisitor from './modals/VisitorReveal.vue';

export default{

    data: () => {

        return {
            storeapp: 'mowgli'
        }
    },
    methods: {
        testStore: () => {
            console.log(this.$store.getters.getTest);

        }
    },

    components: {
        'fd-reveal-visitor': RevealVisitor
    }
}
</script>

Upvotes: 1

Views: 1070

Answers (1)

Srinivas Damam
Srinivas Damam

Reputation: 3045

When arrow syntax used with methods, value of this is not component instance, so this.$store will be undefined.

   methods: {
        testStore: () => {
            console.log(this.$store.getters.getTest); // `this` is window object here.

        }
    },

To avoid this declare methods with out arrow syntax

methods: {
    testStore() {
        console.log(this.$store.getters.getTest);

    }
},

Upvotes: 1

Related Questions