乐闻世界logo
搜索文章和话题

How can you implement route guards in Vue Router to control navigation?

1个答案

1

In Vue Router, implementing route protection is primarily achieved through navigation guards. These are hook functions that execute before route navigation occurs, enabling operations such as authentication checks, data preloading, and conditional navigation. Vue Router provides several types of navigation guards, including global guards, route-level guards, and component-level guards.

Global Guards

Global guards are designed for logic that must run before navigating to any page, such as user authentication.

Example:

javascript
router.beforeEach((to, from, next) => { // Check if the user is logged in if (to.matched.some(record => record.meta.requiresAuth)) { if (!auth.isLoggedIn()) { // Redirect to login page if not authenticated next({ path: '/login' }); } else { // Proceed to target page if authenticated next(); } } else { next(); // Ensure to call next() } });

Route-Level Guards

Route-level guards are invoked only when a specific route is accessed.

Example:

javascript
const router = new VueRouter({ routes: [ { path: '/profile', component: Profile, beforeEnter: (to, from, next) => { if (!auth.isLoggedIn()) { next({ path: '/login' }); } else { next(); } } } ] });

Component-Level Guards

Component-level guards allow you to define guards directly within the route component.

Example:

javascript
export default { beforeRouteEnter(to, from, next) { if (!auth.isLoggedIn()) { next({ path: '/login' }); } else { next(); } } };

By utilizing these guards, you can control user navigation based on login status or other conditions to implement route protection.

2024年10月25日 22:57 回复

你的答案