在 Vue 中使用路由拦截器需要使用 Vue Router 提供的 beforeEach 方法。beforeEach 方法会在每个路由切换前,对路由进行拦截处理。可以在这个方法中进行一些验证或者权限认证,如果满足条件则继续跳转,否则取消跳转并进行相应处理。
下面是一个示例:
- 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 信息,用于验证用户是否已登录。如果用户未登录,但是又尝试访问其他需要登录的页面,则会被重定向到登录页面。如果用户已登录,则自动跳转到访问的页面。
需要注意的是,beforeEach 方法是在路由切换前执行的,因此在其中异步操作需要使用 Promise 来处理。