⭐️ 更多前端技術和知識點,搜索訂閱號
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
首先建立兩個組件 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 的技術文章,只談技術不談八卦 😊