Skip to content
Advertisement

Accessing Vuex state when defining Vue-Router routes

I have the following Vuex store (main.js):

JavaScript

I also have the following routes defined for Vue Router (routes.js):

JavaScript

I’m trying to make it so that, if Vuex stores the user object, and it has the authenticated property set to false, is has the router redirect the user to the login page.

I have this:

JavaScript

The problem is I don’t know how to access the Vuex store’s user object from inside the beforeEach function.

I know that I can have the router guard logic inside components using BeforeRouteEnter, but that would clutter up each component. I want to define it centrally at the router level instead.

Advertisement

Answer

As suggested here, what you can do is to export your store from the file it is in and import it in the routes.js. It will be something like following:

You have one store.js:

JavaScript

Now in routes.js, you can have:

JavaScript

In main.js also you can import store:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement