1. What is a navigation guard?
As its name suggests, the navigation guard provided by vue-router is mainly used to guard navigation by jumping or canceling. There are many ways to build route navigation into it: globally, exclusive to a single route, or at the component level.
Check the following situation:
By default, clicking the homepage link can directly enter the specified interface, but this interface requires the user to log in before accessing, which is a problem
Navigation guards can be set up to detect whether the user is logged in. If he is logged in, he will enter the background page. If he is not logged in, he will force himself to enter the login page, as shown in the figure
2. What types of navigation guards are there?
1. Global guards (3)
Global front guard
Every time a routing navigation jump occurs, the global front guard will be triggered. Therefore, in the global front guard, programmers can control the access rights of each route
1. How to use
You can router/index.js Use router.beforeEach((to, from, next) => {}) in the page to register a global front guard.
2. Code:
// router/index.js 页面 router.beforeEach((to, from, next) => { console.log(to, from); next() });
Global resolution guard
1. Usage method
You can use router.beforeResolve to register a global guard. This is similar to router.beforeEach in that it fires on every navigation, but ensures that the parsing guard is called correctly before the navigation is confirmed, and after all in-component guards and async route components are parsed.
2. Code:
// router/index.js 页面 router.beforeResolve((to, from, next) => { console.log(to,from); next() })
Global post-hook
1. Usage
You can also register a global post-hook, however Unlike guards, these hooks will not accept the next function nor change the navigation itself:
2. Code:
// router/index.js 页面 router.afterEach((to, from) => { console.log(to,from); })
They are useful for auxiliary functions such as analysis, changing page titles, and declaring pages. Useful for many other things.
2. Route exclusive guard (1)
1. Usage method
You can define it directly in the routing configurationbeforeEnter Guard:
2. Code:
// router/index.js 页面(路由规则中) const routes = [ { path: '/home', name: 'Home', component: HomeView, beforeEnter: (to, from,next) => { console.log(to, from); next() }, }, ]
3. Guards within the component (3)
Component There are three internal guards: beforeRouteEnter before the route enters, beforeRouteLeave when the route leaves, and beforeRouteUpdate when the page is updated
beforeRouteEnter(to, from, next)
1. How to use
in the component Used in templates, written at the same level as methods: {}, component routing guards are routing guards written in each separate vue file
2. Code:
// vue 组件内使用 onBeforeRouteUpdate((to, from) => { //当前组件路由改变后,进行触发 console.log(to); });
Note: in vue3 The beforeRouterEnter route guard cannot be used in the setup function.
beforeRouteUpdate(to, from, next)
1. Usage method
Use in the component template, with methods: {} is written at the same level. The component route guard is the route guard written in each separate vue file
2. Code:
// vue 组件内使用 onBeforeRouteUpdate((to, from) => { //当前组件路由改变后,进行触发 console.log(to); });
beforeRouteLeave(to, from, next)
1. The usage method is used in the component template, which is written at the same level as methods: {}. The component routing guard is the routing guard written in each separate vue file
2. Code:
// vue 组件内使用 onBeforeRouteLeave((to, from) => { //离开当前的组件,触发 alert("我离开啦"); });
3. Three parameters of the navigation guard
to: The routing information object to be accessed
from: The one to be left Routing information object
-
next: Function
Call next() to indicate release, allow this route navigation
Call next(false) to indicate no release , this route navigation is not allowed
Calling next({routerPath}) means navigating to this address. Generally, when the user is not logged in, he will navigate to the login interface
Tip: This function can appear multiple times in the navigation guard, but can only be called once!!!
4. How to use beforeRouteEnter in vue3
If you are using the combined API and setup functions to write components, you can add update and leave guards through onBeforeRouteUpdate and onBeforeRouteLeave respectively. Please refer to the Composition API section for more details.
For details, please see the official documentation of vue-router
Navigation Guard | Vue Router
Method 1. We can use The beforeEnter method intercepts, that is, in router.js:
{ path: '/', name: 'home component: () => import('@/xxx.vue'), beforeEnter: (to, from) => { // 可以在定义路由的时候监听from和to } }
Method 2. We can also use the vue2 writing method and use the optional api to use the beforeRouterEnter hook.
<script> export default { beforeRouteEnter(to, from) { console.log('before router enter', to, from) }, mounted() { console.log('mounted') }, }
Five. Simulated login registration case
// 模拟是否登录(true为登录,false为未登录) let token = true router.beforeEach((to, from, next) => { // 判断有没有登录 if (!token) { // 如果没有登录,并且是跳转至登录页 if (to.name == "Login") { // 直接跳转 next(); } else { // 否则直接强制跳转至登录页 router.push('/login') } } else { // 如果已经登录,并且不是跳转至登录页 if (to.name !== "Login") { // 直接跳转 next(); } else { // 否则直接强制跳转至上一个页面 router.push(from.path) } } });
The above is the detailed content of How to use navigation guards in Vue3. For more information, please follow other related articles on the PHP Chinese website!

Netflix chose React to build its user interface because React's component design and virtual DOM mechanism can efficiently handle complex interfaces and frequent updates. 1) Component-based design allows Netflix to break down the interface into manageable widgets, improving development efficiency and code maintainability. 2) The virtual DOM mechanism ensures the smoothness and high performance of the Netflix user interface by minimizing DOM operations.

Vue.js is loved by developers because it is easy to use and powerful. 1) Its responsive data binding system automatically updates the view. 2) The component system improves the reusability and maintainability of the code. 3) Computing properties and listeners enhance the readability and performance of the code. 4) Using VueDevtools and checking for console errors are common debugging techniques. 5) Performance optimization includes the use of key attributes, computed attributes and keep-alive components. 6) Best practices include clear component naming, the use of single-file components and the rational use of life cycle hooks.

Vue.js is a progressive JavaScript framework suitable for building efficient and maintainable front-end applications. Its key features include: 1. Responsive data binding, 2. Component development, 3. Virtual DOM. Through these features, Vue.js simplifies the development process, improves application performance and maintainability, making it very popular in modern web development.

Vue.js and React each have their own advantages and disadvantages, and the choice depends on project requirements and team conditions. 1) Vue.js is suitable for small projects and beginners because of its simplicity and easy to use; 2) React is suitable for large projects and complex UIs because of its rich ecosystem and component design.

Vue.js improves user experience through multiple functions: 1. Responsive system realizes real-time data feedback; 2. Component development improves code reusability; 3. VueRouter provides smooth navigation; 4. Dynamic data binding and transition animation enhance interaction effect; 5. Error processing mechanism ensures user feedback; 6. Performance optimization and best practices improve application performance.

Vue.js' role in web development is to act as a progressive JavaScript framework that simplifies the development process and improves efficiency. 1) It enables developers to focus on business logic through responsive data binding and component development. 2) The working principle of Vue.js relies on responsive systems and virtual DOM to optimize performance. 3) In actual projects, it is common practice to use Vuex to manage global state and optimize data responsiveness.

Vue.js is a progressive JavaScript framework released by You Yuxi in 2014 to build a user interface. Its core advantages include: 1. Responsive data binding, automatic update view of data changes; 2. Component development, the UI can be split into independent and reusable components.

Netflix uses React as its front-end framework. 1) React's componentized development model and strong ecosystem are the main reasons why Netflix chose it. 2) Through componentization, Netflix splits complex interfaces into manageable chunks such as video players, recommendation lists and user comments. 3) React's virtual DOM and component life cycle optimizes rendering efficiency and user interaction management.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version
Chinese version, very easy to use

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),