vue-router is an indispensable part of vue development and an important part of the vue family bucket ecosystem. It is used frequently when developing vue. So in addition to its application on routes, there are some hook functions that can be applied in which places?
There are 6 hook functions for routing
Global routing hook functions: beforeEach, afterEach
Single routing hook function: beforeEnter
Routing hook functions in the component: beforeRouteEnter, beforeRouteLeave, beforeRouteUpdate
Next, I will explain these hook functions in detail
Global navigation hook function
1. vue (global front guard)
BeforeEach's hook function, it is a global before hook function. BeforeEach has to be executed every time every route changes.
Its three parameters:
- to: (Route routing object) The target to be entered The following properties of the routing object to object: path params query hash fullPath matched name meta (under matched, but this example can be used directly)
- from: (Route route object) The route that the current navigation is about to leave
- next: (Function function) Be sure to call this method to resolve the hook. Call method: next (parameter or empty) *** Must call
- next(When there is no parameter): Perform the next hook in the pipeline. If you go to the last hook function, then the navigation state is confirmed (confirmed)
- next('/') or next({ path: '/' }): Jump to a different address. The current navigation is interrupted and a new navigation is performed.
Application scenario: Some page jumps can be processed before the page is redirected, such as intercepting the pages that need to be logged in and making login jumps
((to, from, next) => { if () { //Discern whether the route requires login permission if (cookies('token')) { //Read the token through the encapsulated cookies. If it exists, name will follow the next step. If it does not exist, then jump back to the login page. next()//Don't add "path:/" to next, it will fall into a dead loop } else { next({ path: '/login', query: {redirect: }//Please the jumped route path as a parameter, and jump to the route after logging in successfully }) } } else { next() } })
When entering a new page, make login judgment, administrator authority judgment, browser judgment, etc.
//Use the hook function to transfer permissions to the route((to, from, next) => { const role = ('ms_username'); if(!role && !== '/login'){ next('/login'); }else if(){ // If it is administrator permission, you can enter. This is just a simple simulation of administrator permissions. role === 'admin' ? next() : next('/403'); }else{ // Simple judgment: IE10 and below do not enter rich text editors, and this component is incompatible if(('MSIE') > -1 && === '/editor'){ .$alert('The vue-quill-editor component is not compatible with IE10 and below browsers, please use a higher version of the browser to view', 'Browser Incompatible Notification', { confirmButtonText: 'Sure' }); }else{ next(); } } })
2. vue (global rear guard)
It is after the page is loaded, just like the same, the difference is that it is executed before the page is loaded, but after the page is loaded
3. BeforeEnter router exclusive guard (router hook)
The exclusive route guard beforeEnter is configured in the specified route. You can directly define the beforeEnter guard on the route configuration:
const router = new VueRouter({ routes: [ { path: '/foo', component: Foo, beforeEnter: (to, from, next) => { // ... } } ]
For example, based on the current routing data, determine whether it can be accessed:
const routes = [ { path: '/about', name: 'About', component: About, meta:{ isAuth: false, title:"about" }, children:[ { path: '/detail', name: 'Detail', component: Detail, meta:{ isAuth: false, title:"Details" }, beforeEnter:(to,from,next) =>{ if(){ if(('user')){ next()//To call next will go down } }else{ alert("No permission") } } } ] } ]
Note: If the record has a redirect property, beforeEnter is invalid.
4. Guards within components (navigation hooks within component instances)
- beforeRouteEnter: Before entering this component route
- beforeRouteLeave: Leave this component route
- beforeRouteUpdate: BeforeRouteUpdate will be triggered by the next route switch
const Foo = { template: `...`, beforeRouteEnter (to, from, next) { // Called before rendering the corresponding route of the component is confirmed // No! able! Get component instance `this` // Because the component instance has not been created before the hook is executed }, beforeRouteUpdate (to, from, next) { // Called when the current route changes but the component is reused // For example, for a path with dynamic parameters /foo/:id, when jumping between /foo/1 and /foo/2, // Since the same Foo component is rendered, component instances are reused. And this hook will be called in this case. // Component instances can be accessed `this` }, beforeRouteLeave (to, from, next) { // Called when navigation leaves the corresponding route of this component // Component instances can be accessed `this` }
The actual application is component creation, departure, update, etc.
beforeRouteEnter is the only guard that supports passing callbacks to next. The callback parameters are the current component instance, as follows:
beforeRouteEnter(to, from, next) { ("beforeRouteEnter"); next(vm => { ("vm", vm); //vm is the current component this ("data:", ) // You can get the data of the current component () // Can execute the method of the current component }); }
BeforeRouteLeave application scenarios are all processing triggered when destroying the current component can be added to the hook function. For example, when there is a timer in the component, when the route is switched, you can use beforeRouteLeave to clean up the timer to avoid memory leakage and cause *Error error.
beforeRouteLeave (to, from, next) { () //Clear timer next() }
For example, when there is an unclosed window or unsaved content in the page, the page will be prevented from jumping next(false)
If there is important information on the page, it needs to be saved by the user before it can be redirected
beforeRouteLeave (to, from, next) { (name, content); //Save to localStorage next() }
This is the basic application of the vue-router hook function, and of course there are many other application angles.
For example, beforeRouteEnter can be combined with keep-alive to increase user experience and save resources while obtaining hook nodes.
The component will trigger created when creating, but every time it enters the route, it will trigger beforeRouteEnter. Therefore, when a page uses keep-alive for cache, when it leaves the page and enters again, it will not trigger created again, but beforeRouteEnter will be triggered. At this time, you can use the routing hook for processing.
This is the article about the application summary of the route hook function of vue-router. For more related vue-router routing hooks, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!