文章参考
https://router.vuejs.org/zh-cn/advanced/navigation-guards.html
导航钩子函数
import Vue from 'vue' import Router from 'vue-router' /*首页*/ import zpIndex from '../page/index/zpIndex.vue' Vue.use(Router) var router = new Router({ linkActiveClass: 'open active', scrollBehavior: () => ({y: 0}), routes: [ { path: '/', redirect: '/zpIndex' //路由重定向 }, // 首页 { path: '/zpIndex', name: 'zpIndex', component: zpIndex, beforeEnter: (to, from, next) => { console.log("beforeEnter") next(true); }, beforeLeave (to, from, next) { // 导航离开该组件的对应路由时调用 // 可以访问组件实例 `this` console.log("beforeLeave") next(true); } }, ] }); // 全局路由控制 router.beforeEach((to, from, next) => { console.dir(from); console.log("to : " + to); console.dir(to); // 确保要调用 next 方法,否则钩子就不会被 resolved。 next(true); }); // 全局路由控制 router.afterEach(route => { console.dir(arguments); }) export default router;
- to: Route: 即将要进入的目标 路由对象
- from: Route: 当前导航正要离开的路由
- next: Function: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。
- next(): 进行管道中的下一个钩子。如果全部钩子执行完了,则导航的状态就是 confirmed (确认的)。
- next(false): 中断当前的导航。如果浏览器的 URL 改变了(可能是用户手动或者浏览器后退按钮),那么 URL 地址会重置到 from 路由对应的地址。
- next('/') 或者 next({ path: '/' }): 跳转到一个不同的地址。当前的导航被中断,然后进行一个新的导航。