Skip to content
Advertisement

Vue: Using Vuex store in beforeRouteEnter hook to cancel navigation

I am trying to get vue-router to check a list of permissions, before finishing the navigation to a new route. The permissions are stored in vuex and ideally I’d want to avoid passing them as props everywhere.

When I use the next(vm => {}) callback, regardless of the outcome, it routes to next page, even though it should receive false and cancel the navigation.

beforeRouteEnter(to, undefined, next) {
  next(vm => {
    const allowedRoles = ['Administrator', 'Contributor'];
    if (vm.$store.state.authentication.userInfo.userRoles.some(value => allowedRoles.includes(value))) {
      return true;
    }
    else {
      return false;
    }
  });
}

What am I doing wrong here that is causing it to fail?

Advertisement

Answer

By the time you’ve accessed vm inside next, the navigation has already occurred. Test the value before calling next. You can import the store into the component to access it:

import store from '@/store/index.js';  // import the store
beforeRouteEnter(to, undefined, next) {
  const allowedRoles = ['Administrator', 'Contributor'];
  const roles = store.state.authentication.userInfo.userRoles;
  const isAllowed = roles.some(value => allowedRoles.includes(value))
  next(isAllowed);  // passes `true` or `false` to `next`
},

This way you can access the store without needing the component instance.

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