A
A
askold20132018-02-02 21:37:07
Vue.js
askold2013, 2018-02-02 21:37:07

How to synchronize vuex state in router (vue, vuex-router-sync)?

Hello! Help me figure it out - I'm trying to get a value from state, but I get undefined (the value simply did not have time to load from the server). How can I force beforeEach to wait for the value from state? I tried vuex-router-sync but either I didn’t understand something, or my method doesn’t work.
You must first get user.role and then perform checks.
My code:

import Vue from 'vue';
import VueRouter from 'vue-router';
import routes from './routes';
import { sync } from 'vuex-router-sync';
import { store } from '../store';
Vue.use(VueRouter);

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

router.beforeEach((to, from, next) => {
    const userRole = store.state.usersStore.user.role;
    console.log(userRole);
    if (userRole && (
        (userRole === 'Admin' && to.path === '/edms/admin') ||
        (userRole === 'superAdmin' && to.path === '/edms/superAdmin') // ||
        // ((userRole !== 'superAdmin' || userRole !== 'Admin') && (to.path !== '/edms/admin' || to.path !== '/edms/superAdmin'))
    )) {
        console.log(to.path);
        next();
    }
});

sync(store, router);

export default router;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Riley Usagi, 2018-02-04
@RileyUsagi

I myself am just getting started with Vue, but perhaps my advice will help you.
Try after authorization on the server - to store all user data (including his role) with the client in local storage
. The only difficulty here is that it will be necessary to check the relevance of the data with each request to the server. Or reduce the number of unnecessary requests using JWT technology

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question