一、beforeeach是什麼?
beforeEach是Vue.js提供的一個全局的導航守衛。它可以在跳轉到一個路由前執行一些操作,讓我們能夠控制路由的跳轉。
二、如何使用beforeeach?
在Vue3中,我們可以通過使用router.beforeEach實例方法,向全局添加一個導航守衛。
// main.js
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
history: createWebHistory(),
routes: [...]
})
router.beforeEach((to, from, next) => {
// do something before navigation
next()
})
在上述代碼中,我們使用了createRouter來創建路由實例,然後在實例中使用beforeEach方法來添加一個導航守衛。在beforeEach的參數中,它可以接收三個參數。
to: Route: 即將要進入的目標Route對象。from: Route: 當前導航正要離開的路由。next: Function: 一定要調用該方法來 resolve 這個鉤子。執行效果依賴next方法的調用參數。
三、常見的使用場景
1、校驗用戶登錄狀態
在實際項目中,常常需要校驗用戶是否已經登錄了。在使用beforeEach方法時,我們可以在其中添加一個校驗邏輯,來實現路由的跳轉攔截。
// main.js
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
history: createWebHistory(),
routes: [...]
})
router.beforeEach((to, from, next) => {
if (to.meta.auth && !isLogin) {
next('/login')
}
else {
next()
}
})
在上述代碼中,to.meta.auth表示需要登錄才能訪問的路由,isLogin表示用戶是否處於登錄狀態。如果用戶未登錄並且要訪問需要登錄才能訪問的路由,則跳轉到登錄頁面;否則放行。
2、路由切換時展示loading
在路由切換時,有時候需要一些視覺上的效果,比如加載一個loading。我們可以在beforeEach中添加相應的邏輯,來控制loading的顯示與隱藏。
// main.js
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
history: createWebHistory(),
routes: [...]
})
router.beforeEach((to, from, next) => {
// show loading
next()
})
router.afterEach(() => {
// hide loading
})
在上述代碼中,我們在beforeEach中添加顯示loading的邏輯,在路由跳轉完成後,在afterEach中添加隱藏loading的邏輯。這樣,我們就能在路由切換時展示loading了。
3、路由動態添加title
在每個路由頁面中,常常需要為頁面添加一個標題。可以通過路由的meta屬性來動態添加標題。
const router = createRouter({
history: createWebHistory(),
routes: [
{
path: '/',
name: 'Home',
component: Home,
meta: { title: '首頁' } // 添加 meta 屬性
},
...
]
})
router.beforeEach((to, from, next) => {
if (to.meta.title) {
document.title = to.meta.title // 修改網頁標題
}
next()
})
在上述代碼中,我們在每個路由的meta屬性中添加了一個title屬性,表示該路由的標題。在beforeEach中,我們可以根據該meta屬性來動態修改網頁標題。
四、總結
本文詳細講解了Vue3中的beforeEach導航守衛的作用和使用方法。同時,還介紹了一些常見的使用場景,包括校驗用戶登錄狀態、路由切換時展示loading、路由動態添加title等。希望對Vue3開發者有所幫助。
原創文章,作者:PNQTA,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/349299.html
微信掃一掃
支付寶掃一掃