当前位置:首页 > VUE

vue路由拦截怎么实现

2026-01-22 14:33:28VUE

Vue路由拦截的实现方法

在Vue中,可以通过路由守卫(Navigation Guards)来实现路由拦截,主要用于权限控制、登录验证等场景。

全局前置守卫

使用router.beforeEach注册全局前置守卫,在路由跳转前进行拦截:

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

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!auth.loggedIn()) {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    } else {
      next()
    }
  } else {
    next()
  }
})

路由独享守卫

在路由配置中直接定义beforeEnter守卫:

vue路由拦截怎么实现

const router = new VueRouter({
  routes: [
    {
      path: '/dashboard',
      component: Dashboard,
      beforeEnter: (to, from, next) => {
        if (!store.getters.isAuthenticated) {
          next('/login')
        } else {
          next()
        }
      }
    }
  ]
})

组件内守卫

在组件内部使用beforeRouteEnterbeforeRouteUpdatebeforeRouteLeave

export default {
  beforeRouteEnter(to, from, next) {
    // 不能获取组件实例`this`
    next(vm => {
      // 通过`vm`访问组件实例
    })
  },
  beforeRouteUpdate(to, from, next) {
    // 当前路由改变但组件被复用时调用
    next()
  },
  beforeRouteLeave(to, from, next) {
    // 导航离开该组件时调用
    if (confirm('确定要离开吗?')) {
      next()
    } else {
      next(false)
    }
  }
}

全局解析守卫

使用router.beforeResolve注册全局守卫,在导航被确认前调用:

vue路由拦截怎么实现

router.beforeResolve((to, from, next) => {
  // 适合获取数据或执行其他异步操作
  next()
})

全局后置钩子

使用router.afterEach注册全局后置钩子,不会改变导航本身:

router.afterEach((to, from) => {
  // 适合分析、更改页面标题等操作
  document.title = to.meta.title || '默认标题'
})

路由元信息

配合路由元信息meta可以更灵活地控制权限:

const router = new VueRouter({
  routes: [
    {
      path: '/admin',
      component: Admin,
      meta: { requiresAuth: true, roles: ['admin'] }
    }
  ]
})

动态添加路由

通过router.addRoutes动态添加路由实现权限过滤:

// 过滤有权限的路由
const accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
router.addRoutes(accessedRoutes)

以上方法可以单独使用或组合使用,根据项目需求选择最合适的实现方式。路由守卫的执行顺序为:全局前置守卫→路由独享守卫→组件内守卫→全局解析守卫→全局后置钩子。

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

相关文章

vue实现点击跳转路由

vue实现点击跳转路由

Vue 实现点击跳转路由的方法 在 Vue 中实现点击跳转路由可以通过以下几种方式完成,具体取决于项目使用的路由管理工具(通常是 Vue Router)以及需求场景。 使用 router-link…

vue列表实现

vue列表实现

Vue 列表实现方法 使用 v-for 指令 v-for 是 Vue 中用于渲染列表的核心指令,基于数据源动态生成 DOM 元素。语法格式为 item in items 或 (item, index)…

vue实现详情

vue实现详情

Vue 实现详情页的常见方法 使用动态路由 在 Vue Router 中配置动态路由参数,通过 $route.params 获取详情 ID。示例路由配置: { path: '/detail/:i…

vue实现handsontable

vue实现handsontable

Vue 中实现 Handsontable 要在 Vue 项目中集成 Handsontable,可以使用官方提供的 @handsontable/vue 封装库。以下是一个完整的实现步骤。 安装依赖…

vue实现cs

vue实现cs

Vue 实现 CS(Client-Side)渲染的常见方法 Vue.js 是一个用于构建用户界面的渐进式框架,默认采用客户端渲染(CSR)。以下是几种常见的实现方式: 使用 Vue CLI 创建项…

vue实现oauth

vue实现oauth

Vue 实现 OAuth 的步骤 安装必要的依赖 确保项目中安装了 axios 和 vue-router。OAuth 通常需要发送 HTTP 请求和处理路由跳转。 npm install axios…