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.
JavaScript
x
12
12
1
beforeRouteEnter(to, undefined, next) {
2
next(vm => {
3
const allowedRoles = ['Administrator', 'Contributor'];
4
if (vm.$store.state.authentication.userInfo.userRoles.some(value => allowedRoles.includes(value))) {
5
return true;
6
}
7
else {
8
return false;
9
}
10
});
11
}
12
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:
JavaScript
1
2
1
import store from '@/store/index.js'; // import the store
2
JavaScript
1
7
1
beforeRouteEnter(to, undefined, next) {
2
const allowedRoles = ['Administrator', 'Contributor'];
3
const roles = store.state.authentication.userInfo.userRoles;
4
const isAllowed = roles.some(value => allowedRoles.includes(value))
5
next(isAllowed); // passes `true` or `false` to `next`
6
},
7
This way you can access the store without needing the component instance.