I have a dynamic role system which admin can add or delete the role. I search how to add role in vue router in meta as array base on this role access level I am trying to add it via store it not working. How can get roles from API and set it in vue router? maybe I doing the wrong way because I am new to vuejs can any help me out thanks.
I am tried to add vuex store to add router meta but I have roles in store not setting it on the router meta
name: 'Home',
component: Home,
children: [
{
path: '/users',
meta: { label: 'Users', role: store.getters.roles },
component: Users
}]```
``` path: '/',
name: 'Home',
component: Home,
children: [
{
path: '/users',
meta: { label: 'Users', role: ['admin','staf'] },
component: Users
}, ```
Because the (non-reactive) routes object is created before the relevant information in the vuex store is present (as most likely your API request isn't yet fulfilled), store.getters.roles
is still empty or null. A solution would be to instead put a function in the meta object that can be called whenever the access-system does its role-checking: meta: { roles: () => store.getters.roles }
. Simply check against route.meta.roles()
upon navigation requests.
I am not exactly sure what you're trying to do with the vuex store, but I guess you're trying to keep 'Home' accessible for all roles. What I'd suggest doing is simply removing the role
field from these routes (I'd also rename it to roles
, as it can be multiple, but that's up to you). Then, to enforce the access-system use something along the lines of:
router.beforeEach((to, from, next) => {
const user = yourAuthentication.user
const lacksRole = to.matched.some(route => {
return route.meta.roles && !route.meta.roles.includes(user.role)
})
if (lacksRole) {
return next(false) // Aborts the navigation request
}
// Route either doesn't require any role or user has one of the
// roles specified in the route meta object, continue navigation
next()
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.