How to use Vuex in Router

Hi ,
I’m having a problem with using together router and vuex
I’m trying to console log getter in router.js but every time I get error : Cannot read property ‘getters’ of undefined
Tried to import store into router and without importing

store.js

import Vue from 'vue'
import Vuex from 'vuex'
import moment from 'moment'
import auth from './auth'

Vue.use(Vuex)

export const store = new Vuex.Store({
//everything is inside
})

router.js

import VueRouter from 'vue-router';
import Dashboard from '../components/Dashboard';
import Login from '../components/Login';
import Home from '../components/content/Home';
import UrediRezervaciju from '../components/content/UrediRezervaciju';
import UrediGosta from '../components/content/UrediGosta';
import {store} from '../store/store'

// this is the problem
//Everything is woring without this
console.log(this.$store.getters.isAuthenticated)

let routes = [
	{
		path: '/',
		component: Dashboard,
		children: [
			{path: '/', component: Home},
			{path: '/urediRezervaciju/:reservation_id', component: UrediRezervaciju},
			{path: '/urediGosta/:guest_id', component: UrediGosta},
		],
		beforeEnter: (to, from, next)=>{

            if(localStorage.getItem("token") ) {
            	next();
            }
            else next('/login');

        }
	},
	{
		path: '/login',
		component: Login,
		beforeEnter: (to, from, next)=>{

            if(!localStorage.getItem("token")) next();
            else next('/');

        }
	}
];

export default new VueRouter({
	routes
})

app.js

import Pocetna from './Pocetna';
import router from './router/router'; 

import {store} from './store/store';

const app = new Vue({
    el: '#app',
    render: h=>h(Pocetna),
    store,
    router
});
1 Like

You are not inside a component, so this.$store does not work.

You already correctly import the store, so just access it through your imported object:

store.getters.isAuthenticated

6 Likes

Thank you Linus for all you do.