使用 Vue Router 的编程式导航,可以在路由文件中进行判断和跳转,实现路由菜单跳转同级菜单的功能。

当目标菜单不存在时,可以自动跳转到同级菜单的第一个菜单项。

const router = new VueRouter({
  routes: [
    {
      path: '/menu1',
      component: Menu1
    },
    {
      path: '/menu2',
      component: Menu2
    },
    {
      path: '/menu3',
      component: Menu3
    }
  ]
})

router.beforeEach((to, from, next) => {
  const menuList = ['menu1', 'menu2', 'menu3'] // 定义菜单列表
  if (menuList.indexOf(to.name) === -1) { // 判断当前菜单是否存在
    const siblings = to.matched[0].parent.children // 获取同级菜单列表
    const firstSibling = siblings[0] // 获取同级菜单中的第一个菜单项
    next({ path: firstSibling.path }) // 跳转到同级菜单中的第一个菜单项
  } else {
    next() // 跳转到当前菜单
  }  
})

在上述代码中,定义了一个菜单列表 menuList,用于验证当前菜单是否存在。如果不存在,则获取同级菜单列表 siblings,并跳转到同级菜单中的第一个菜单项 firstSibling;如果存在,则直接跳转到当前菜单。

使用 Vue Router 的 beforeEach 函数,在路由跳转前进行判断和跳转,实现了路由菜单跳转同级菜单的功能。

Vue Router: 路由菜单跳转同级菜单的实现

原文地址: https://www.cveoy.top/t/topic/oCFF 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录