vue-router2

六,导航钩子
导航钩子函数主要是在导航跳转的时候做一些操作,比如跳转页面之前,进行判断 进而选择跳转到哪里

钩子函数根据生效范围根据其生效范围可以分为全局钩子函数,路由独享钩子函数 和 组件钩子函数、

全局钩子函数
在路由文件里 对全局进行拦截数据
router.beforeEach((to, from, next)=>{
  next();
});
router.afterEach((to, from, next) => {
    console.log(to.path);
});

 上面方法接受三个参数

   to: 下个路由

   from: 正离开的路由

  next: 一定要调用该方法来resolve钩子

  next() 进行管道中的下一个钩子。如果全部钩子执行完了,则导航的状态就是 confirmed(确定的)。

  next(false). 中断当前的导航。

next('/')next({path: '/'}), 跳转到一个不同的地址。当前的导航被中断,然后进行一个新的导航。

路由钩子函数:

 将上述方法写在路由里

{
      path: '/helloworld',
      name: 'HelloWorld',
      component: resolve => require(['@/views/HelloWorld'], resolve), // 使用懒加载
      beforeEnter(to, from, next) {
        console.log(111)
        console.log(to.path); // 打印 /helloworld
        console.log(from.path); // 打印 /
        next(); // 跳到/helloworld 组件页面
      }
    },

组件内钩子函数

更细的拦截 

组件内放钩子

 beforeRouteEnter(to, from, next) {
    // 在渲染该组件的对应路由被 confirm 前调用
    // 不!能!获取组件实例 `this`
    // 因为当钩子执行前,组件实例还没被创建
    console.log(to.path); // 打印 /helloworld
    console.log(from.path); // 打印 /
    next();  // 跳转到 /helloworld 指定的页面
  },
  beforeRouteUpdate (to, from, next) {
    // 在当前路由改变,但是该组件被复用时调用
    // 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
    // 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
    // 可以访问组件实例 `this`
  },
  beforeRouteLeave (to, from, next) {
    // 导航离开该组件的对应路由时调用
    // 可以访问组件实例 `this`
  }

路由钩子使用场景: 登录态校验 权限校验等

路由滚动行为

mode为history时有效

scrollBehavior (to, from, savedPosition) {
    // return 期望滚动到哪个的位置
  }
//所有路由新页面滚动到顶部:
scrollBehavior (to, from, savedPosition) {
  return { x: 0, y: 0 }
}

//如果有锚点
scrollBehavior (to, from, savedPosition) {
  if (to.hash) {
    return {
      selector: to.hash
    }
  }
}

 以上滚动目前新版路由已经不支持了

原文地址:https://www.cnblogs.com/moneyss/p/8618617.html