当前位置:首页 > VUE

vue实现路由拦截

2026-02-20 10:52:28VUE

路由拦截的实现方式

在Vue中实现路由拦截通常使用Vue Router的导航守卫功能。导航守卫允许在路由跳转前、跳转后或跳转过程中执行自定义逻辑,常用于权限控制、登录验证等场景。

全局前置守卫

通过router.beforeEach注册全局前置守卫,每次路由跳转前都会触发。以下是一个检查用户是否登录的示例:

const router = new VueRouter({ ... })

router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('token')
  if (to.meta.requiresAuth && !isAuthenticated) {
    next('/login')
  } else {
    next()
  }
})

路由独享守卫

在路由配置中直接定义beforeEnter守卫,只对特定路由生效:

vue实现路由拦截

const router = new VueRouter({
  routes: [
    {
      path: '/admin',
      component: Admin,
      beforeEnter: (to, from, next) => {
        if (user.role !== 'admin') next('/403')
        else next()
      }
    }
  ]
})

组件内守卫

在组件内部使用导航守卫,包括beforeRouteEnterbeforeRouteUpdatebeforeRouteLeave

export default {
  beforeRouteEnter(to, from, next) {
    // 不能访问组件实例
    next(vm => {
      // 通过vm访问组件实例
    })
  },
  beforeRouteLeave(to, from, next) {
    const answer = confirm('确定要离开吗?')
    if (answer) next()
    else next(false)
  }
}

元字段权限控制

结合路由的meta字段实现更细粒度的权限控制:

vue实现路由拦截

const routes = [
  {
    path: '/dashboard',
    component: Dashboard,
    meta: { requiresAuth: true, roles: ['admin', 'editor'] }
  }
]

router.beforeEach((to, from, next) => {
  const userRole = getUserRole()
  if (to.meta.roles && !to.meta.roles.includes(userRole)) {
    next('/403')
  } else {
    next()
  }
})

动态路由处理

对于动态加载的路由,可以在路由加载完成后添加全局守卫:

function loadRoutes() {
  return fetchRoutes().then(routes => {
    router.addRoutes(routes)
    router.beforeEach((to, from, next) => {
      // 守卫逻辑
    })
  })
}

错误处理

捕获并处理导航过程中的错误:

router.onError(error => {
  console.error('路由错误:', error)
  if (error.name === 'NavigationDuplicated') {
    // 处理重复导航错误
  }
})

以上方法可以根据实际需求组合使用,构建完整的路由拦截系统。注意避免在守卫中出现无限循环的导航跳转。

标签: 路由vue
分享给朋友:

相关文章

vue实现sso

vue实现sso

Vue 实现 SSO(单点登录)方案 单点登录(SSO)允许用户通过一次登录访问多个相关系统。以下是基于 Vue 的实现方案: 使用 OAuth2/OpenID Connect 协议 OAuth2…

vue实现高亮

vue实现高亮

Vue 实现文本高亮的方法 在 Vue 中实现文本高亮可以通过多种方式完成,以下是几种常见的方法: 方法一:使用 v-html 指令 通过 v-html 指令可以动态插入 HTML 内容,将需要高…

vue实现批量

vue实现批量

Vue 实现批量操作的方法 在 Vue 中实现批量操作通常涉及选择多个项目并执行统一处理,例如批量删除、批量更新等。以下是几种常见实现方式: 表格多选批量操作 使用 el-table 配合复选框实现…

vue实现active

vue实现active

Vue 实现 active 状态的方法 在 Vue 中实现 active 状态可以通过以下几种方式实现,具体取决于使用场景和需求。 使用 v-bind:class 动态绑定类名 通过 v-bind:…

vue实现toggle

vue实现toggle

Vue 实现 Toggle 功能 在 Vue 中实现 toggle(切换)功能可以通过多种方式完成,以下是几种常见的方法: 使用 v-model 和 v-on 通过 v-model 绑定数据,结合…

vue jwt实现

vue jwt实现

Vue JWT 实现方法 安装依赖 确保项目中安装了 jsonwebtoken(后端)和 axios(前端)。若使用 Vue 3,可搭配 vue-router 和 pinia(或 vuex)管理状态。…