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

What are the three types of Navigation Guards available in Vue.js ?

1个答案

1

In Vue.js, there are three main types of navigation guards, which provide the ability to intercept and control routing changes. These are highly applicable for scenarios requiring logic execution during route transitions, such as validating user permissions, saving edited information, or simply logging.

Global Guards:

These are configured on the global router instance and affect every route. In Vue Router, you can set these guards using methods like beforeEach, beforeResolve, and afterEach.

For example, using beforeEach to confirm if the user is logged in:

javascript
router.beforeEach((to, from, next) => { if (to.matched.some(record => record.meta.requiresAuth) && !authService.isLoggedIn()) { next({ path: '/login', query: { redirect: to.fullPath } }); } else { next(); } });

Per-Route Guards:

These guards run only on the routes where they are defined. In route configuration, you can define them using beforeEnter.

For example, if only specific routes require user authentication, you can:

javascript
{ path: '/secure', component: SecureComponent, beforeEnter: (to, from, next) => { if (!authService.isLoggedIn()) { next({ path: '/login', query: { redirect: to.fullPath } }); } else { next(); } } }

In-Component Guards:

These guards can be directly used within Vue components, such as beforeRouteEnter, beforeRouteUpdate, and beforeRouteLeave. They are used for handling component-level logic.

For example, prompting to save data before leaving the component:

javascript
export default { data() { return { // Component data }; }, beforeRouteLeave(to, from, next) { if (this.unsavedChanges) { const answer = window.confirm('You have unsaved changes. Are you sure you want to leave?'); if (answer) { next(); } else { next(false); } } else { next(); } } }

These three guards provide flexible methods for handling routing transition logic at different levels, helping developers build more complex and user-friendly web applications.

2024年10月25日 23:11 回复

你的答案