menu和路由刷新匹配

352 阅读1分钟

该项目git地址

  • 结合项目源码更容易看懂 代码更完整
  • 这是一整个系列 可以看看之前的文章 能了解数据是怎么封装的

问题

  • 要实现一个默认选中的效果

    • 页面刷新之后 上方的路由地址会跟 上一次点击到的页面不匹配

实现

  • elementPlus menu 有一个属性 :default-active="defaultValue"

  • 只需要动态传递之前点击的 id 就可以实现效果了

    • 那么怎么获取 之前的 id 呢?

    • 封装一个工具函数 具体实现

      • export function pathMapToMenu(
          userMenus: any[],
          currentPath: string,
          breadcrumbs?: IBreadcrumb[]
        ): any {
          console.log(userMenus, currentPath)
          for (const menu of userMenus) {
            // 1 代表外层 会递归遍历向里面查找
            if (menu.type === 1) {
              // 这里接收深层递归返回的结果
              const findMenu = pathMapToMenu(menu.children ?? [], currentPath)
              // 这里将最终找到的结果返回出去
              if (findMenu) {
                breadcrumbs?.push({ name: menu.name })
                breadcrumbs?.push({ name: findMenu.name })
                return findMenu
              }
              // 找到了 将找到的结果返回
            } else if (menu.type === 2 && menu.url === currentPath) {
              return menu
            }
          }
        }
        
    • 使用这个函数能够将当前的 路由信息 返回出去

      • // 获取当前路由路径
        const router = useRouter()
        const route = useRoute()
        const currentPath = route.path// 更新面包屑对应的内容
        const menu = pathMapToMenu(userMenus.value, currentPath)
        // 定义默认的 menu 选中 第一次进入页面 或者刷新之后 选中的 menu
        console.log(menu)
        /*
        + 这里有个小坑 就是 第一次进来的时候 路径是 /main
          + 那么不可能匹配到路由  返回的就是 undefined 就会报错
        + 解决方法
          + 就是匹配到 /main 的时候在进行一次重定向就行了
        */
        const defaultValue = ref(menu.id + '')
        
      • \