What is a route guard
Router guard is a mechanism provided by Vue Router to control and manage routes during navigation. By using the route guard, you can execute the corresponding logic before, after, and when error handling.
Vue Router provides three types of routing guards:
1、Global front guard
2、The guards exclusively for routes
3、Guards within components
Global front guard
Global front guard (): These guards will be called before route switching and can be used for permission verification, login status check and other operations. Common global front guards are beforeEach.
grammar
:
((to, from, next) => { // Logic executed before each route navigation triggers});
Specific configuration in router/
// import Vue from 'vue'; import VueRouter from 'vue-router'; (VueRouter); const router = new VueRouter({ //Routing configuration routes: [ // ...Define the route... ] }); ((to, from, next) => { // Global front guard logic}); export default router;
In the above example, weMethod registers a global front guard. The guard is called before each route navigation. The guard's callback function receives three parameters:
-
to
: The target routing object that is about to jump -
from
: The route object that the current navigation is about to leave -
next
: Callback function used to control navigation behavior
In the guard's callback function, you can perform corresponding operations according to business needs, such as verifying user permissions, checking login status, canceling navigation or redirecting to other routes.next
Functions are used to control the continuation or interruption of navigation.
- To interrupt the current navigation and cancel the jump, you can call
next(false)
。 - To redirect to another route and want to interrupt the current navigation, you can call
next('/other-route')
。 - If no interruption of navigation is required, call
next()
Allow navigation to continue.
Global before Guards can work in the following scenarios:
- Login Verification: You can use the global front guard to verify that the user is logged in. By checking the user's login status or verifying the user's identity information, unauthorized users can be prevented from accessing pages that require login permissions.
- Permission Control: Global Pre-guard can be used to implement role-based or permission-based access control. By checking the user's role or permissions in the guard, users can only access the pages they have permissions, and perform corresponding processing when there is no permission, such as jumping to an error page or prompting no permission information.
- Route Intercept: Before you do route navigation, you can use the global front guard to intercept, modify, or redirect navigation. Depending on specific conditions or business needs, you can handle navigation in the guard, such as canceling navigation, modifying target routes, or jumping to other pages.
- Data preprocessing: Sometimes, before entering a route, you may need to load, initialize or verify the relevant data. Global Front Guard helps you perform these preprocessing tasks before navigation occurs, ensuring that data preparation is completed before entering the target route.
The guards exclusively for routes
The guards exclusively for routes (beforeEnter
): These guards can be defined directly in the routing configuration and only take effect on specific routes. The corresponding logic may be performed before entering the route, before leaving the route, or between the two. Common routes exclusive guards have beforeEnter.
grammar
const router = new VueRouter({ routes: [ { path: '/example',//Specific jump path component: ExampleComponent,//Specific page jump beforeEnter: (to, from, next) => { // Exclusive guard logic in a single route } }, // ... ] });
Specific configuration in router/
// import Vue from 'vue'; import VueRouter from 'vue-router'; (VueRouter); const routes = [ { path: '/example', component: ExampleComponent, beforeEnter: (to, from, next) => { // Exclusive guard logic in a single route } }, // ...Other routing configurations...]; const router = new VueRouter({ routes }); export default router;
The route-exclusive guard is very useful in the following scenarios:
- Authentication and permission control: You can use the route-exclusive guard to verify the identity and permissions of users. For example, for a specific route that requires login to access, you can check in its exclusive guard whether the user is already logged in, and if not logged in, it prevents navigation to that route.
- Data loading and processing: Sometimes, you need to load some data or perform some asynchronous operations before entering a certain route. In the route-exclusive guard, you can call the API to request data, ensuring that the data is loaded before continuing to navigate to the target route.
- Navigation Control: In some cases, you may want to control navigation behavior based on certain conditions, such as canceling navigation, redirecting to other routes, etc. By making conditional judgments in the guards exclusively for routes and calling appropriate navigation methods, precise control of navigation behavior can be achieved.
- Logging or burying points: If you need to log or perform statistical analysis on a specific route, you can use the route-exclusive guard to trigger the corresponding operation. For example, log access logs or send statistics when entering a route.
Guards within components
Guards within components: These guards are methods written directly inside components and are used to react to routing changes within components. Common components guards include beforeRouteEnter, beforeRouteUpdate and beforeRouteLeave.
Guards within components allow you to execute corresponding logic within components for different stages of the component life cycle.
Here are the guards within the provided components:
-
beforeRouteEnter
: Called before entering the route, but before the component instance is created, so the component instance cannot be accessed. You can get component instances by passing in a callback or use Promise to delay entry. -
beforeRouteLeave
: Called when leaving the current route. It can be used to confirm whether to leave the page, save temporary data, etc. -
beforeRouteUpdate
: Called when the current route is multiplexed, that is, the parameters change but the component instance is still multiplexed. The parameters can be responded to changes in this guard.
These guards can be defined directly in component optionsgrammar
export default { // ... beforeRouteEnter(to, from, next) { // Call before component instance is created // You can use a callback function or return a Promise delay entry }, beforeRouteLeave(to, from, next) { // Called when leaving the current route // Can perform operations such as confirmation, saving data, etc. }, beforeRouteUpdate(to, from, next) { // Called when the current route is reused // Can respond to changes in parameters } // ... }
Guards within components are very useful in the following scenarios:
- Verify user identity: Before entering a route, you can pass
beforeRouteEnter
The guard verifies the user's login status or permissions. If the user is not logged in or does not have sufficient permission to access the route, you can cancel the navigation or redirect to another page. - Loading asynchronous data: You can use it before entering a route
beforeRouteEnter
The guard gets asynchronous data and renders the component after the data is loaded. This ensures that the component will not be displayed after the data is loaded, and avoids display problems due to the data not loaded. - Cancel navigation: You can use it before leaving the current route
beforeRouteLeave
The guard makes some judgments and actions, such as checking whether the form has been modified and asking the user whether it needs to save unsubmitted data. Depending on the user's choice, you can cancel the navigation or continue to the next route. - Conditional Rendering and Dynamic Routing:
beforeRouteUpdate
In the guard, you can update the component's data or re-request data according to the changes in the current routing parameters. This allows you to dynamically display content or refresh component status according to different routing parameters.
Give an example
In Vue development, you can use the route navigation guard to display the login page first without logging in without displaying the home page.
The route navigation guard provides some hook functions that can be intercepted and controlled during route navigation. in,beforeEach
Navigation guards can be triggered before each route switch.
Use the route navigation guard to display the login page before logging in:
// import Vue from 'vue'; import App from './'; import router from './router'; // Global routing navigation guard((to, from, next) => { const isLoggedIn = checkUserLoggedIn(); //Judge whether the user is logged in based on actual conditions if ( !== '/login' && !isLoggedIn) { // If the user is not logged in and is not accessing a login page, redirect to the login page next('/login'); } else { // If you have logged in or accessed the login page, it will jump normally next(); } }); new Vue({ router, render: (h) => h(App) }).$mount('#app');
In the above code, webeforeEach
Make a judgment in the navigation guard. If the user is not logged in and the login page is not visited (i.e./login
path), then usenext('/login')
Redirect the user to the login page; otherwise, if the user is logged in or is accessing the login page, continue to jump normally.
In this way, the login status is checked before each route switch, and the check result is determined whether to redirect to the login page. This way you can display the login page first instead of the home page first.
When a user visits other pages that require login to view, he will be blocked and redirected to the login page. After the user logs in successfully, he will jump to the page he originally wanted to visit.
Please note thatcheckUserLoggedIn()
It is a custom function that is used to actually determine whether the user is logged in. Please write the function according to your actual needs and authentication logic.
This is the end of this article about the detailed explanation of Vue Router Guard. For more related Vue Router Guard content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!