用vue写个菜单组件,一级菜单在顶部,二级菜单在左侧
时间: 2023-05-24 11:00:53 浏览: 315
好的,以下是一个简单的Vue菜单组件代码,一级菜单在顶部,二级菜单在左侧。
```
<template>
<div class="menu">
<ul class="menu-list">
<li v-for="(item, index) in menuList" :key="index" :class="{ 'active': activeIndex === index }" @click="toggleActive(index)">
{{ item.title }}
<ul class="submenu" v-if="item.children">
<li v-for="(subItem, subIndex) in item.children" :key="subIndex" :class="{ 'active': activeSubIndex === subIndex }" @click="toggleSubActive(subIndex)">
{{ subItem.title }}
</li>
</ul>
</li>
</ul>
</div>
</template>
<script>
export default {
name: 'Menu',
data() {
return {
activeIndex: 0,
activeSubIndex: 0,
menuList: [
{
title: '一级菜单1',
children: [
{ title: '二级菜单1' },
{ title: '二级菜单2' }
]
},
{
title: '一级菜单2',
children: [
{ title: '二级菜单3' }
]
},
{
title: '一级菜单3'
}
]
};
},
methods: {
toggleActive(index) {
if (this.activeIndex === index) {
this.activeIndex = -1;
} else {
this.activeIndex = index;
}
this.activeSubIndex = -1;
},
toggleSubActive(index) {
this.activeSubIndex = index;
}
}
};
</script>
<style scoped>
.menu {
background-color: #eee;
}
.menu-list {
display: flex;
justify-content: space-between;
align-items: center;
list-style: none;
padding: 0;
margin: 0;
}
.menu-list li {
cursor: pointer;
margin: 0 10px;
padding: 10px;
}
.menu-list li.active {
background-color: #ccc;
}
.submenu {
display: none;
position: absolute;
background-color: #fff;
list-style: none;
padding: 0;
margin: 0;
}
.menu-list li:hover > .submenu {
display: block;
}
.submenu li {
padding: 10px;
}
.submenu li.active {
background-color: #ccc;
}
</style>
```
这是一个简单的可折叠菜单,当你点击一级菜单时,它会展开或收起二级菜单。你可以根据你的需求修改这个组件。