zoukankan      html  css  js  c++  java
  • 导航守卫

    1.router.beforeEach

    router.beforeEach((to, from, next) => {
      // ...
    })
    

     在执行所有路由之前之前,内部守卫,外部守卫之前。next执行了,才能resolve这个钩子,才能跳转。如果没有执行next(),那么下一步的to的跳转不执行。

    next(): 进行管道中的下一个钩子。如果全部钩子执行完了,则导航的状态就是 confirmed (确认的)。
    
    next(false): 中断当前的导航。如果浏览器的 URL 改变了 (可能是用户手动或者浏览器后退按钮),那么 URL 地址会重置到 from 路由对应的地址。
    
    next('/') 或者 next({ path: '/' }): 跳转到一个不同的地址。当前的导航被中断,然后进行一个新的导航。你可以向 next 传递任意位置对象,且允许设置诸如 replace: true、name: 'home' 之类的选项以及任何用在 router-link 的 to prop 或 router.push 中的选项。
    
    next(error): (2.4.0+) 如果传入 next 的参数是一个 Error 实例,则导航会被终止且该错误会被传递给 router.onError() 注册过的回调。
    

      

    2.router.beforeResolve

    const router = new beforeResolve({ ... })
    
    router.beforeEach((to, from, next) => {
      // ...
    })
    会在内部路由执行之后再执行。内部组件和组件内守卫不next(),那么解析守卫就不执行。

    3.全局后置钩子
    router.afterEach((to, from) => {
      // ...
    })
    

      没有next()。只是看的

    4.路由独享的守卫

    const router = new VueRouter({
      routes: [
        {
          path: '/foo',
          component: Foo,
          beforeEnter: (to, from, next) => {
            // ...
          }
        }
      ]
    })
    

      执行早于router.beforeResolve, 但是晚于router.beforeEach,也早于组件内部的守卫

    5.组件内部的钩子

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

      

    这个离开守卫通常用来禁止用户在还未保存修改前突然离开。该导航可以通过 next(false) 来取消。

    beforeRouteLeave (to, from , next) {
      const answer = window.confirm('Do you really want to leave? you have unsaved changes!')
      if (answer) {
        next()
      } else {
        next(false)
      }
    }
    

      

     

  • 相关阅读:
    Idea 找不到tomcat server 服务器选项
    idea永久使用
    Jax
    我的2014
    Mysql锁机制
    mysql 查询效率提升
    Java 静态工厂方法
    java 面试题(转)
    Java Semaphore
    Java CyclicBarrier
  • 原文地址:https://www.cnblogs.com/chenyi4/p/11362972.html
Copyright © 2011-2022 走看看