当前位置:首页 > VUE

vue 实现动态路由

2026-03-28 17:11:13VUE

实现动态路由的基本思路

动态路由的核心是根据用户权限或数据动态生成路由表。Vue Router 支持通过 addRoute 方法动态添加路由规则。

定义静态基础路由

静态路由是无需权限即可访问的页面(如登录页、404页等):

const constantRoutes = [
  {
    path: '/login',
    component: () => import('@/views/login.vue')
  },
  {
    path: '/404',
    component: () => import('@/views/404.vue')
  }
]

获取动态路由数据

通常从后端接口获取用户权限对应的路由配置,数据结构示例:

[
  {
    "path": "/dashboard",
    "component": "Layout",
    "children": [
      {
        "path": "index",
        "component": "dashboard/index"
      }
    ]
  }
]

路由数据转换

需要将后端返回的组件路径字符串转换为真正的组件:

function loadView(view) {
  return () => import(`@/views/${view}.vue`)
}

function filterAsyncRoutes(routes) {
  return routes.map(route => {
    if (route.component) {
      if (route.component === 'Layout') {
        route.component = Layout
      } else {
        route.component = loadView(route.component)
      }
    }
    if (route.children) {
      route.children = filterAsyncRoutes(route.children)
    }
    return route
  })
}

动态添加路由

在用户登录后或应用初始化时添加路由:

import router from './router'

const asyncRoutes = filterAsyncRoutes(backendRoutes)
asyncRoutes.forEach(route => {
  router.addRoute(route)
})

// 添加404兜底路由(需最后添加)
router.addRoute({ path: '/:pathMatch(.*)', redirect: '/404' })

路由权限控制

结合 Vue Router 的导航守卫实现权限校验:

router.beforeEach((to, from, next) => {
  if (hasToken()) {
    if (to.path === '/login') {
      next('/')
    } else {
      if (hasRoles()) {
        next()
      } else {
        getRoutes().then(routes => {
          // 动态添加路由逻辑
          next({ ...to, replace: true })
        })
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})

菜单生成方案

动态路由通常需要配合动态菜单使用:

function generateMenu(routes) {
  return routes.filter(route => {
    if (route.meta && route.meta.hidden) return false
    if (route.children) {
      route.children = generateMenu(route.children)
    }
    return true
  })
}

常见问题处理

路由刷新404问题:需要确保服务器配置支持 History 模式:

location / {
  try_files $uri $uri/ /index.html;
}

路由重复添加问题:在添加动态路由前可先重置:

vue 实现动态路由

function resetRouter() {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher
}

完整示例代码

// permission.js
router.beforeEach(async (to, from, next) => {
  if (store.getters.token) {
    if (!store.getters.routes.length) {
      const { routes } = await store.dispatch('user/getRoutes')
      const accessRoutes = await store.dispatch('permission/generateRoutes', routes)
      accessRoutes.forEach(route => {
        router.addRoute(route)
      })
      next({ ...to, replace: true })
    } else {
      next()
    }
  } else {
    next('/login')
  }
})

通过以上方案可以实现完整的动态路由系统,包括路由权限控制、菜单动态生成等功能。实际项目中可根据需求调整数据结构和权限校验逻辑。

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

相关文章

vue动态组建实现原理

vue动态组建实现原理

Vue动态组件的实现原理 Vue的动态组件主要通过<component>标签和is属性实现,其核心原理涉及以下机制: 动态组件基础语法 <component :is="curren…

vue实现路由跳转

vue实现路由跳转

路由跳转的基本方法 在Vue中,路由跳转可以通过vue-router实现。vue-router是Vue.js官方的路由管理器,用于构建单页面应用(SPA)。以下是几种常见的路由跳转方式。 声明式导航…

Vue中实现路由

Vue中实现路由

Vue 路由的实现方法 在 Vue 中实现路由通常使用 Vue Router 库。以下是具体的实现步骤: 安装 Vue Router 通过 npm 或 yarn 安装 Vue Router: n…

php 路由实现的

php 路由实现的

PHP 路由实现方法 基于原生 PHP 实现路由 创建一个简单的路由解析器,通过解析 URL 路径来调用对应的控制器或函数。 // 定义路由表 $routes = [ '/' => '…

vue实现hash路由

vue实现hash路由

vue实现hash路由的基本原理 Vue实现hash路由主要依赖浏览器原生的hashchange事件和Vue的响应式系统。hash路由通过监听URL中#后面的变化来切换页面内容,无需向服务器发起请求。…

vue实现动态弧线

vue实现动态弧线

Vue 实现动态弧线的方法 动态弧线可以通过 SVG 或 Canvas 实现,以下是两种常见的方法: 使用 SVG 实现动态弧线 SVG 的 <path> 元素可以绘制弧线,结合…