• Vue 递归多级菜单

Vue 递归多级菜单

⭐️ 更多前端技术和知识点,搜索订阅号 JS 菌 订阅

考虑以下菜单数据:

[  {    name: "About",    path: "/about",    children: [      {        name: "About US",        path: "/about/us"      },      {        name: "About Comp",        path: "/about/company",        children: [          {            name: "About Comp A",            path: "/about/company/A",            children: [              {                name: "About Comp A 1",                path: "/about/company/A/1"              }            ]          }        ]      }    ]  },  {    name: "Link",    path: "/link"  }];

需要实现的效果:

首先创建两个组件 Menu 和 MenuItem

// Menuitem<template>  <li class="item">    <slot />  </li></template>

MenuItem 是一个 li 标签和 slot 插槽,允许往里头加入各种元素

<!-- Menu --><template>  <ul class="wrapper">    <!-- 遍历 router 菜单数据 -->    <menuitem :key="index" v-for="(item, index) in router">      <!-- 对于没有 children 子菜单的 item -->      <span class="item-title" v-if="!item.children">{{item.name}}</span>      <!-- 对于有 children 子菜单的 item -->      <template v-else>        <span @click="handleToggleShow">{{item.name}}</span>        <!-- 递归操作 -->        <menu :router="item.children" v-if="toggleShow"></menu>      </template>    </menuitem>  </ul></template><script>  import MenuItem from "./MenuItem";  export default {    name: "Menu",    props: ["router"], // Menu 组件接受一个 router 作为菜单数据    components: { MenuItem },    data() {      return {        toggleShow: false // toggle 状态      };    },    methods: {      handleToggleShow() {        // 处理 toggle 状态的是否展开子菜单 handler        this.toggleShow = !this.toggleShow;      }    }  };</script>

Menu 组件外层是一个 ul 标签,内部是 vFor 遍历生成的 MenuItem

这里有两种情况需要做判断,一种是 item 没有 children 属性,直接在 MenuItem 的插槽加入一个 span 元素渲染 item 的 title 即可;另一种是包含了 children 属性的 item 这种情况下,不仅需要渲染 title 还需要再次引入 Menu 做递归操作,将 item.children 作为路由传入到 router prop

最后在项目中使用:

<template>  <div class="home">    <menu :router="router"></menu>  </div></template><script>  import Menu from '@/components/Menu.vue'  export default {    name: 'home',    components: {      Menu    },    data () {      return {        router: // ... 省略菜单数据      }    }  }</script>

最后增加一些样式:

MenuItem:

<style lang="stylus" scoped>  .item {    margin: 10px 0;    padding: 0 10px;    border-radius: 4px;    list-style: none;    background: skyblue;    color: #fff;  }</style>

Menu:

<style lang="stylus" scoped>  .wrapper {    cursor: pointer;    .item-title {      font-size: 16px;    }  }</style>
Menu 中 ul 标签内的代码可以单独提取出来,Menu 作为 wrapper 使用,递归操作部分的代码也可以单独提取出来

请关注我的订阅号,不定期推送有关 JS 的技术文章,只谈技术不谈八卦 ????