Vue动态路由问题

动态路由分为

  • 1.前端控制
  • 2.后端控制(数据库存储)
const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

const routes = []
// 只有静态路由需要注册

涉及到的相关知识--路由守卫

路由守卫总共有7个

全局路由守卫:

beforeEach 前置守卫

affterEach 后置守卫

beforeResolve 解析守卫
路由中会有参数->三个参数所代表的含义:

  • 1.to 表示要去哪里
  • 2.from 表示从哪里来
  • 3.next 表示是否方向

路由守卫简介:

路由守卫主要用来通过跳转或取消的方式守卫导航。有多种机会植入路由导航过程中:全局的, 单个路由独享的, 或者组件级的。
可以简单的理解为一座房子的门口的保安,想要进入这个房子就必须通过保安的检查,要告诉路由守卫你从哪里来?总不能随便陌生人就给放进去?要到哪里去?然后保安再告诉你下一步该怎么做?如果你的确是这个房子主人允许进入的人,那就让你进入,否则就要打电话给房子主人,跟房主商量(登录注册),给你权限。

动态路由

// 注意:刷新页面会导致页面路由重置
export const setRoutes = () => {
  const storeMenus = localStorage.getItem("menus"); //获取用户的menus,来动态拼接路由
  if (storeMenus) {//若menus不为空

    // 获取当前的路由对象名称数组
    const currentRouteNames = router.getRoutes().map(v => v.name)
    if (!currentRouteNames.includes('Manage')) {
      // 拼装动态路由
      const manageRoute = { path: '/', name: 'Manage', component: () => import('../views/Manage.vue'), redirect: "/home", children: [
          { path: 'person', name: '个人信息', component: () => import('../views/Person.vue')},
          { path: 'password', name: '修改密码', component: () => import('../views/Password.vue')},
        ] }
      const menus = JSON.parse(storeMenus)
      menus.forEach(item => {
        if (item.path) {  // 当且仅当path不为空的时候才去设置路由
          let itemMenu = { path: item.path.replace("/", ""), name: item.name, component: () => import('../views/' + item.pagePath + '.vue')}
          manageRoute.children.push(itemMenu)
        } else if(item.children.length) {//设置当前路由的子路由
          item.children.forEach(item => {
            if (item.path) {
              let itemMenu = { path: item.path.replace("/", ""), name: item.name, component: () => import('../views/' + item.pagePath + '.vue')}
              manageRoute.children.push(itemMenu)
            }
          })
        }
      })
      // 动态添加到现在的路由对象中去
      router.addRoute(manageRoute)
    }

  }
}
posted @ 2022-08-08 14:42  还要再努力一些吧  阅读(81)  评论(0)    收藏  举报