Vue 递归多级菜单

Vue 递归多级菜单

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

考虑如下菜单数据:css

[
  {
    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"
  }
];
复制代码

须要实现的效果:html

20190503142723.png

首先建立两个组件 Menu 和 MenuItem前端

// Menuitem

<template>
  <li class="item">
    <slot />
  </li>
</template>
复制代码

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

<!-- 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 遍历生成的 MenuItemjava

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

最后在项目中使用:ui

<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>
复制代码

最后增长一些样式:this

MenuItem:spa

<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 菌公众帐号

请关注个人订阅号,不按期推送有关 JS 的技术文章,只谈技术不谈八卦 😊

相关文章
相关标签/搜索