路由把关者- Navigation Guards

前言

Vue Router 提供 Navigation Guards,可以在路由变更前後去呼叫相关的 function。


使用?

利用router.beforeEach 注册全域 before guards

const router = new VueRouter({ ... })

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

to: 即将要进入的路由
from: 从何处离开到这的路由
next: 往下执行的 callback

在路由跳转结束後触发afterEach (不会影响路由跳转)

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

在 route 物件内注册,可依照规则决定是否要注册 hook

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

在元件中...

单一元件中也有 Hooks 可以用

  • beforeRouteEnter
    • 路由尚未进入元件时
  • beforeRouteUpdate
    • 当路由被改变,但元件还是同一个时
  • beforeRouteLeave
    • 当路由要离开这个元件时

ex:

const Foo = {
  template: `...`,
  beforeRouteEnter(to, from, next) {
    // 还无法取得 this
  },
  beforeRouteUpdate(to, from, next) {
    // called when the route that renders this component has changed.
    // This component being reused (by using an explicit `key`) in the new route or not doesn't change anything.
    // 例如 `/foo/1` and `/foo/2`, 都是用到 foo 这个实体
  },
  beforeRouteLeave(to, from, next) {
    // 离开当下
  }
}

顺序

Navigation lifecycle diagram

取自[Docs] Incomplete Navigation Resolution Flow

start beforeRouteLeave 离开路由(元件)
----> beforeEach 进入新的路由前(全域)
----> beforeEnter 进入新的路由前
----> beforeRouteEnter 路由尚未进入元件时
----> beforeResolve 路由和搭配元件已被解析
----> afterEach 路由跳转完
----> beforeCreate 元件建立前
----> created 元件已建立
----> beforeMount 挂载前
----> mounted 挂载完成


下篇预告

  • Composition API
  • Navigation Guards 实例 这个下下回

每日一句:
对自己加油,还有 3 天 /images/emoticon/emoticon02.gif


<<:  Day 27 : 快速排序法 Quick Sort

>>:  Angular Stock上市个股日成交(一)(Day27)

Unity自主学习(十六):认识Unity介面(7)

那麽前几天都在摸索的主要区块,也只剩下"属性检视区" 如同字面的意思,这边会显示...

JS 如何运行 DAY45

这里要开始介绍 JS核心 首先要先来介绍 JS究竟是怎样运行的 其实浏览器(Browser)是看不懂...

自动化测试,让你上班拥有一杯咖啡的时间 | Day 15 - 设定环境变量

此系列文章会同步发文到个人部落格,有兴趣的读者可以前往观看喔。 在测试时,当要测试的环境有许多种,...

Day 24. Test Server Side Rendering

Test Server Side Rendering 开宗明义地说: 你无法使用 Vue Test ...

Day 24:专案06 - 股市趋势图01 | 单月股市API、Pandas

各位早安,今天是第24天,但其实爬虫的技巧大致上已经教得差不多了,而且我猜会看我的文章的人,应该都想...