Vue · Senior · Question 39 of 75
How do you implement role-based access with route meta?
{ path: "/admin", component: Admin, meta: { roles: ["admin"] } }
router.beforeEach((to) => {
const roles = to.matched.flatMap((r) => r.meta.roles ?? []);
if (roles.length && !roles.some(auth.hasRole)) return { name: "forbidden" };
});- ✓Correct answer: Check
to.matchedso meta from parent routes applies to their children too - 2Read only
to.meta, which already includes all parents' meta - 3Put the check in each component's template
Explanation
to.meta is a shallow merge of parent and child meta, so child values overwrite parent ones; to.matched gives each level separately. Type meta via RouteMeta module augmentation.