網(wǎng)站建設(shè) 建站知識人民政府網(wǎng)站
在 Vue 中使用路由攔截器需要使用 Vue Router 提供的 beforeEach 方法。beforeEach 方法會在每個路由切換前,對路由進行攔截處理。可以在這個方法中進行一些驗證或者權(quán)限認證,如果滿足條件則繼續(xù)跳轉(zhuǎn),否則取消跳轉(zhuǎn)并進行相應(yīng)處理。
下面是一個示例:
import Vue from 'vue'
import Router from 'vue-router'
import Login from '@/views/Login.vue'Vue.use(Router)const router = new Router({routes: [{path: '/',name: 'home',component: Home},{path: '/dashboard',name: 'dashboard',component: Dashboard},{path: '/login',name: 'login',component: Login}]
})router.beforeEach((to, from, next) => {const isAuthenticated = localStorage.getItem('token')if (to.name !== 'login' && !isAuthenticated) {next({ name: 'login' })} else {next()}
})export default router
在這個示例中,使用了 localStorage 來保存用戶的 token 信息,用于驗證用戶是否已登錄。如果用戶未登錄,但是又嘗試訪問其他需要登錄的頁面,則會被重定向到登錄頁面。如果用戶已登錄,則自動跳轉(zhuǎn)到訪問的頁面。
需要注意的是,beforeEach 方法是在路由切換前執(zhí)行的,因此在其中異步操作需要使用 Promise 來處理。