Vue 3 中階
路由守衛有哪些?
什麼是路由守衛?
路由守衛(Route Guards)是 Vue Router 提供的導航攔截機制,讓我們可以在路由切換前後執行邏輯,例如驗證登入狀態、設定頁面標題、記錄訪問日誌等。
三大類型
1. 全域守衛(Global Guards)
對所有路由生效。
const router = createRouter({ /* ... */ })
// 全域前置守衛(最常用)
router.beforeEach((to, from, next) => {
const isAuthenticated = !!localStorage.getItem('token')
if (to.meta.requiresAuth && !isAuthenticated) {
next({ name: 'Login' }) // 重導向至登入頁
} else {
next() // 繼續導航
}
})
// 全域後置鉤子(導航完成後執行,無 next)
router.afterEach((to, from) => {
document.title = to.meta.title || '我的網站'
})
2. 路由獨享守衛(Per-Route Guards)
在路由設定中定義,只對該路由生效。
const routes = [
{
path: '/admin',
component: AdminPage,
beforeEnter: (to, from, next) => {
if (!isAdmin()) {
next({ name: 'Home' })
} else {
next()
}
}
}
]
3. 組件內守衛(In-Component Guards)
在組件中定義,只對該組件生效。
// Options API
export default {
beforeRouteEnter(to, from, next) {
// 組件尚未建立,無法存取 this
next(vm => { /* vm 是組件實例 */ })
},
beforeRouteUpdate(to, from, next) {
// 路由參數改變但組件複用(如 /user/1 → /user/2)
next()
},
beforeRouteLeave(to, from, next) {
// 離開頁面前,可用於確認是否有未儲存資料
if (this.hasUnsavedChanges) {
if (!confirm('有未儲存的變更,確定離開?')) return
}
next()
}
}
執行順序
beforeEach(全域)beforeEnter(路由獨享)beforeRouteEnter(組件內)- 解析非同步路由組件
afterEach(全域,導航完成)
常見應用
| 場景 | 建議守衛 |
|---|---|
| 登入驗證 | router.beforeEach |
| 設定頁面標題 | router.afterEach |
| 頁面權限控制 | beforeEnter + meta |
| 離開前確認 | beforeRouteLeave |
✦ AI 模擬面試
輸入你的答案,AI 即時分析精準度與改進空間
登入後即可使用 AI 評分
