当前位置:首页 > VUE

vue实现登录动态路由

2026-01-20 06:09:53VUE

实现登录动态路由的基本思路

动态路由的核心是根据用户权限或角色,在登录后动态加载可访问的路由表。Vue Router 提供了 addRoutes 方法(Vue Router 4.x 使用 addRoute)实现这一功能。

定义静态路由和动态路由

静态路由包括无需权限的页面(如登录页、404页),动态路由则根据用户权限生成:

vue实现登录动态路由

// 静态路由
const constantRoutes = [
  { path: '/login', component: Login },
  { path: '/404', component: NotFound }
]

// 动态路由(示例)
const asyncRoutes = [
  { path: '/admin', component: Admin, meta: { roles: ['admin'] } },
  { path: '/user', component: User, meta: { roles: ['user', 'admin'] } }
]

路由守卫处理登录逻辑

在全局前置守卫中检查用户权限,动态添加路由:

router.beforeEach(async (to, from, next) => {
  const hasToken = localStorage.getItem('token')

  if (to.path === '/login') {
    next()
    return
  }

  if (!hasToken) {
    next('/login')
    return
  }

  if (store.getters.routes.length === 0) {
    try {
      const roles = await store.dispatch('user/getUserInfo')
      const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
      router.addRoutes(accessRoutes)
      next({ ...to, replace: true })
    } catch (error) {
      next('/login')
    }
  } else {
    next()
  }
})

Vuex 状态管理

通过 Vuex 管理路由状态和权限数据:

vue实现登录动态路由

const store = new Vuex.Store({
  state: {
    routes: [],
    addRoutes: []
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      state.addRoutes = routes
      state.routes = constantRoutes.concat(routes)
    }
  },
  actions: {
    generateRoutes({ commit }, roles) {
      return new Promise(resolve => {
        let accessedRoutes
        if (roles.includes('admin')) {
          accessedRoutes = asyncRoutes
        } else {
          accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
        }
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      })
    }
  }
})

function filterAsyncRoutes(routes, roles) {
  return routes.filter(route => {
    if (route.meta && route.meta.roles) {
      return roles.some(role => route.meta.roles.includes(role))
    } else {
      return true
    }
  })
}

动态菜单渲染

根据生成的路由表渲染侧边栏菜单:

<template>
  <div v-for="route in permission_routes" :key="route.path">
    <router-link :to="route.path">{{ route.meta.title }}</router-link>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
export default {
  computed: {
    ...mapGetters(['permission_routes'])
  }
}
</script>

处理404页面

动态路由添加后,需将404页面路由放在最后:

const router = new VueRouter({
  routes: constantRoutes
})

// 添加动态路由后
router.addRoutes([
  ...accessedRoutes,
  { path: '*', redirect: '/404', hidden: true }
])

注意事项

  1. 路由的 name 属性必须唯一,否则可能导致路由添加失败
  2. Vue Router 3.x 使用 addRoutes,4.x 使用 addRoute 逐个添加
  3. 刷新页面时需要重新获取用户权限信息
  4. 后端返回的路由数据通常需要转换为组件引用(如 component: () => import('@/views/...')

标签: 路由动态
分享给朋友:

相关文章

vue实现动态隐藏

vue实现动态隐藏

动态隐藏的实现方法 在Vue中实现动态隐藏可以通过多种方式,常见的有条件渲染、动态绑定样式或类名。以下是几种具体实现方法: 使用v-if或v-show指令 <template> &…

vue实现动态表单

vue实现动态表单

Vue 动态表单实现方法 使用 v-for 动态渲染表单字段 通过遍历数组动态生成表单项,数据驱动视图变化。表单字段配置可存储在数组中,修改数组即可实现表单动态更新。 <template>…

vue动态加载实现

vue动态加载实现

Vue动态加载实现方法 动态加载在Vue中通常指按需加载组件或资源,以下是几种常见实现方式: 使用异步组件 通过defineAsyncComponent或动态import()语法实现组件按需加载:…

vue路由跳转实现

vue路由跳转实现

Vue 路由跳转实现方法 在 Vue 中,路由跳转可以通过多种方式实现,以下是常见的几种方法: 声明式导航(模板中使用 <router-link>) 通过 <router-link…

动态路由vue实现

动态路由vue实现

动态路由的实现方式 在Vue中实现动态路由通常有两种主要方式:基于用户权限的动态路由和基于参数变化的动态路由。这两种方式都能有效提升应用灵活性。 基于用户权限的动态路由 通过用户角色或权限动态生成可…

实现vue动态绑定

实现vue动态绑定

动态绑定的基本语法 在Vue中,使用v-bind指令或简写:实现动态绑定,将数据属性与HTML元素的属性关联起来。例如动态绑定class或style: <div v-bind:class="{…