Vue:ルーターのbeforeEachおよびafterEachフック関数
Vue Routers Beforeeach
When routing a jump, we need some permission judgment or other operations. This time you need to use the hook function of the route. Definition: The routing hook is mainly a function defined for the user to perform some special processing when the route changes. In general, vue provides three major types of hooks, two functions. 1, the global hook 2, the hook of a route 3, the components inside the hook Two functions: 1, Vue.beforeEach(function(to,form,next){}) /*Execute before the jump */ 2.Vue.afterEach(function(to,form))/*Judges after the jump*/ Global hook function As the name suggests, it is a function that is valid globally. router.beforeEach((to, from, next) => { let token = router.app.$storage.fetch('token') let needAuth = to.matched.some(item => item.meta.login) if(!token && needAuth) return next({path: '/login'}) next() }) The beforeEach function has three parameters: To: route object to be entered by router From: the route that the current navigation is about to leave. Next:Function, a hook in the pipeline. If the execution is finished, the status of the navigation is confirmed (confirmed) otherwise, it is false, and the navigation is terminated. afterEach function does not pass the next() function Hook function of a route As the name suggests, it is a function written in a route, essentially no different from the function inside the component. Copy code const router = new VueRouter({ routes: [ { path: '/login', component: Login, beforeEnter: (to, from, next) => { // ... }, beforeLeave: (to, from, next) => { // ... } } ] }) Copy code Routing component hook Note: This is the routing component! The routing component belongs to the component, but the component is not equivalent to the routing component! The so-called routing component: directly defines the components at the component in the router. Such as: Copy code var routes = [ { path:'/home', component:home, name:'home' } ] Copy code Invalid when calling the hook function of a route in a child component. This is defined in the official documentation: The following route navigation hooks can be directly defined within the routing component. beforeRouteEnter beforeRouteUpdate (2.2 new) beforeRouteLeave Here is a brief description of the use of the hook function: it is level with data, methods. Copy code beforeRouteLeave(to, from, next) { next() }, beforeRouteEnter(to, from, next) { next() }, beforeRouteUpdate(to, from, next) { next() }, data:{}, method: {}