How to analyze Vue router routing Guard
This article is about how to analyze Vue router routing guards. I think it is very practical, so I share it with you. I hope you can get something after reading this article. Let's take a look at it.
1. Global pre-beforeEach
When the name stored in Local Storage is zhangsan, click on the message to display the message content.
1. Global front beforeEach
Add a routing guard beforeEach to router
Syntax:
Router.beforeEach ((to, from, next) = > {})
Function: call the functions in beforeEach during initialization and before each route switch
Parameters:
1.to: destination rout
2.from: routing before hopping
3.next: release
two。 Realize
II. Demand II
If there are many paths that need to be judged before jumping, you need to write a lot of judgment code, and the judgment structure will be very complex.
At this time, you can put a meta tag in the route that needs to be judged.
Meta tags provide metadata about HTML documents (metadata refers to data used to describe data)
At this point, you can use the tag field in meta to judge.
Third, the global guard afterEach
AfterEach and beforeEach are used in the same way.
The difference is that afterEach does not have the parameter next.
1. Change title to your own title
Assign each route its own title name
Const router = new VueRouter ({routes: [{name: 'home', path:' / home', component: Home, meta: {title: "Home"}, children: [{name: "xiaoxi", path: 'message', component: Message Meta: {title: "message"}, children: [{name: 'xiangqing', path:' detail', component: Detail, meta: {isAuth: true Title: "message details"}]}]}, {path:'/ about', component: About, meta: {title: "about"}}]})
Modify the title name in beforEach
Router.afterEach ((to, from) = > {document.title = to.meta.title | | "Test"}) IV. BeforeRouteEnter in the component
Through routing rules, it is called when entering the component
2. BeforeRouteLeave
Through routing rules, it is called when leaving the component
The above is how to analyze the Vue router routing guard, the editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.