Vue 遞歸多級菜單

Vue 遞歸多級菜單

⭐️ 更多前端技術和知識點,搜索訂閱號 JS 菌 訂閱

考慮如下菜單數據:html

[
  {
    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"
  }
];

須要實現的效果:前端

20190503142723.png

首先建立兩個組件 Menu 和 MenuItemvue

// Menuitem

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

MenuItem 是一個 li 標籤和 slot 插槽,容許往裏頭加入各類元素app

<!-- 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 遍歷生成的 MenuItemui

這裏有兩種狀況須要作判斷,一種是 item 沒有 children 屬性,直接在 MenuItem 的插槽加入一個 span 元素渲染 item 的 title 便可;另外一種是包含了 children 屬性的 item 這種狀況下,不只須要渲染 title 還須要再次引入 Menu 作遞歸操做,將 item.children 做爲路由傳入到 router propthis

最後在項目中使用:spa

<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>

最後增長一些樣式:code

MenuItem:component

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

Menu:router

<style lang="stylus" scoped>
  .wrapper {
    cursor: pointer;

    .item-title {
      font-size: 16px;
    }
  }
</style>
Menu 中 ul 標籤內的代碼能夠單獨提取出來,Menu 做爲 wrapper 使用,遞歸操做部分的代碼也能夠單獨提取出來

JS 菌公衆帳號

請關注個人訂閱號,不按期推送有關 JS 的技術文章,只談技術不談八卦 😊

相關文章
相關標籤/搜索