• vue 路由钩子


    路由钩子分为三种

    • 全局钩子: beforeEach、 afterEach、beforeResolve
    • 单个路由里面的钩子: beforeEnter
    • 组件路由:beforeRouteEnter、 beforeRouteUpdate、 beforeRouteLeave

    它的三个参数:

    to: (Route路由对象) 即将要进入的目标 路由对象 to对象下面的属性: path params query hash fullPath matched name meta(在matched下,但是本例可以直接用)

    from: (Route路由对象) 当前导航正要离开的路由

    next: (Function函数) 一定要调用该方法来 resolve 这个钩子。 调用方法:next(参数或者空) ***必须调用

    next(无参数的时候): 进行管道中的下一个钩子,如果走到最后一个钩子函数,那么 导航的状态就是 confirmed (确认的)

    全局钩子

    1. beforeEach: 页面加载之前
    2. afterEach: 页面加载之后
    3. beforeResolve: 用的比较少,和beforeEach类似
    router.beforeEach((to,from,next) => {
      console.log('beforeEach ===',to,from)
      next()
    })
    
    router.beforeResolve((to,from,next) => {
      console.log('beforeResolve ===',to,from)
      next()
    })
    
    router.afterEach((to,from) => {
      console.log('afterEach ===',to,from)
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    路由独享守卫

    beforeEnter: 路由配置上直接定义 beforeEnter 守卫

      {
        path: '/',
        name: 'Home',
        component: Home,
        beforeEnter: (to,from,next) => {
          console.log('beforeEnter ==', to,from)
          next()
        }
      }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    路由组件内的守卫

    1. beforeEach:在渲染该组件的对应路由被 confirm 前调用
    2. afterEach: 当前路由改变,但是该组件被复用时调用
    3. beforeResolve: 导航离开该组件的对应路由时调用
      beforeRouteEnter: (to,from,next) => {
        console.log('beforeRouteEnter ==', to,from)
        // 不!能!获取组件实例 `this`
        // 因为当钩子执行前,组件实例还没被创建
        next()
      },
    
      beforeRouteUpdate: (to,from,next) => {
        console.log('beforeRouteUpdate ==', to,from)
        // 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
        // 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
        // 可以访问组件实例 `this`
        next()
      },
    
      beforeRouteLeave: (to,from,next) => {
        console.log('beforeRouteLeave ==', to,from)  // 可以访问组件实例 `this`
            // 业务使用场景:
        	// 1.清除定时器
        	// 2.当页面中有未关闭的窗口, 或未保存的内容时, 阻止页面跳转
        next()
      },
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    路由执行顺序

    在这里插入图片描述

  • 相关阅读:
    第3章 基础项目的搭建
    这两款简洁好看的软件你确定不想要吗
    第6章:表单中的受控组件与非受控组件
    【分析思路】测试数据分析思路
    牛客小白月赛59
    在Kubernetes上部署Spring Boot微服务实践
    Flink Yarn Per Job - 提交应用
    Z-Libary最新地址检测,再也不用担心找不到ZLibary了
    JuiceFS v1.0 beta2 发布|进一步提升稳定性
    【CV】第 15 章:结合计算机视觉和 NLP 技术
  • 原文地址:https://blog.csdn.net/GXY1551705593/article/details/127415406