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) {
// 離開當下
}
}
start beforeRouteLeave
離開路由(元件)
----> beforeEach
進入新的路由前(全域)
----> beforeEnter
進入新的路由前
----> beforeRouteEnter
路由尚未進入元件時
----> beforeResolve
路由和搭配元件已被解析
----> afterEach
路由跳轉完
----> beforeCreate
元件建立前
----> created
元件已建立
----> beforeMount
掛載前
----> mounted
掛載完成
每日一句:
對自己加油,還有 3 天