網(wǎng)站建設(shè)和管理河南百度推廣代理商
在 Vue 中使用路由攔截器需要使用 Vue Router 提供的 beforeEach 方法。beforeEach 方法會(huì)在每個(gè)路由切換前,對(duì)路由進(jìn)行攔截處理??梢栽谶@個(gè)方法中進(jìn)行一些驗(yàn)證或者權(quán)限認(rèn)證,如果滿足條件則繼續(xù)跳轉(zhuǎn),否則取消跳轉(zhuǎn)并進(jìn)行相應(yīng)處理。
下面是一個(gè)示例:
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
在這個(gè)示例中,使用了 localStorage 來保存用戶的 token 信息,用于驗(yàn)證用戶是否已登錄。如果用戶未登錄,但是又嘗試訪問其他需要登錄的頁面,則會(huì)被重定向到登錄頁面。如果用戶已登錄,則自動(dòng)跳轉(zhuǎn)到訪問的頁面。
需要注意的是,beforeEach 方法是在路由切換前執(zhí)行的,因此在其中異步操作需要使用 Promise 來處理。