vue实现左侧菜单
Vue 实现左侧菜单的方法
使用 Element UI 的 el-menu 组件
安装 Element UI 后,可以直接使用其提供的 el-menu 组件快速构建左侧菜单。以下是一个基本示例:
<template>
<el-menu
default-active="1"
class="el-menu-vertical"
background-color="#545c64"
text-color="#fff"
active-text-color="#ffd04b"
>
<el-submenu index="1">
<template #title>
<i class="el-icon-location"></i>
<span>导航一</span>
</template>
<el-menu-item index="1-1">选项1</el-menu-item>
<el-menu-item index="1-2">选项2</el-menu-item>
</el-submenu>
<el-menu-item index="2">
<i class="el-icon-menu"></i>
<span>导航二</span>
</el-menu-item>
</el-menu>
</template>
<style>
.el-menu-vertical {
height: 100vh;
}
</style>
自定义 Vue 组件实现
如果需要完全自定义的左侧菜单,可以创建一个 Vue 组件:
<template>
<div class="sidebar">
<div v-for="item in menuItems" :key="item.id" class="menu-item">
<div class="menu-title" @click="toggleSubMenu(item)">
{{ item.title }}
<span class="arrow" :class="{ 'arrow-down': item.isOpen }"></span>
</div>
<div v-show="item.isOpen" class="submenu">
<div v-for="subItem in item.children" :key="subItem.id" class="submenu-item">
{{ subItem.title }}
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
menuItems: [
{
id: 1,
title: '导航一',
isOpen: false,
children: [
{ id: 1-1, title: '选项1' },
{ id: 1-2, title: '选项2' }
]
},
{
id: 2,
title: '导航二',
isOpen: false,
children: []
}
]
}
},
methods: {
toggleSubMenu(item) {
item.isOpen = !item.isOpen
}
}
}
</script>
<style>
.sidebar {
width: 200px;
background-color: #545c64;
color: white;
height: 100vh;
}
.menu-item {
padding: 10px;
}
.menu-title {
cursor: pointer;
display: flex;
justify-content: space-between;
}
.submenu {
padding-left: 20px;
}
.submenu-item {
padding: 5px 0;
cursor: pointer;
}
.arrow {
display: inline-block;
width: 0;
height: 0;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-top: 5px solid white;
transition: transform 0.3s;
}
.arrow-down {
transform: rotate(180deg);
}
</style>
结合 Vue Router 实现导航
左侧菜单通常需要与路由配合使用:
<template>
<el-menu
:default-active="$route.path"
class="el-menu-vertical"
router
>
<el-menu-item index="/home">
<i class="el-icon-menu"></i>
<span>首页</span>
</el-menu-item>
<el-menu-item index="/about">
<i class="el-icon-document"></i>
<span>关于</span>
</el-menu-item>
</el-menu>
</template>
响应式设计考虑
为了使左侧菜单在不同屏幕尺寸下表现良好,可以添加响应式设计:

@media (max-width: 768px) {
.el-menu-vertical {
width: 60px;
}
.el-menu-item span {
display: none;
}
}






