<template>
  <ul>
    <li v-for="item in menu" :key="item.name">
      <router-link :to="item.path" exact>{{ item.name }}</router-link>
      <template v-if="item.children">
        <Menu :menu="item.children" />
      </template>
    </li>
  </ul>
</template>
<script>
export default {
  name: "Menu",
  props: {
    menu: {
      type: Array,
      required: true,
    },
  },
  methods: {
    jumpToRoute(route) {
      this.$router.push(route);
    },
  },
  mounted() {
    const currentRoute = this.$route.path;
    const currentMenu = this.menu.find((item) => item.path === currentRoute);

    if (currentMenu) {
      // 当前菜单存在对应路由,直接跳转
      this.jumpToRoute(currentRoute);
    } else {
      // 当前菜单不存在对应路由,跳转同级菜单
      const siblings = this.menu.filter(
        (item) => item.parent === this.menu[0].parent
      );
      const firstSibling = siblings.find((item) => item.path !== undefined);
      if (firstSibling) {
        this.jumpToRoute(firstSibling.path);
      }
    }
  },
};
</script>
Vue 菜单跳转: 找不到当前路由则跳转同级菜单

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

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