侧边菜单vue实现
侧边菜单的 Vue 实现方法
使用 Vue 实现侧边菜单可以通过多种方式完成,以下是几种常见的实现方法:
使用 Vue Router 和动态组件
通过 Vue Router 可以实现侧边菜单的导航功能,结合动态组件可以灵活切换内容。

<template>
<div class="sidebar">
<ul>
<li v-for="item in menuItems" :key="item.path">
<router-link :to="item.path">{{ item.title }}</router-link>
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
menuItems: [
{ path: '/home', title: 'Home' },
{ path: '/about', title: 'About' },
{ path: '/contact', title: 'Contact' }
]
}
}
}
</script>
<style>
.sidebar {
width: 200px;
background-color: #f5f5f5;
height: 100vh;
position: fixed;
left: 0;
top: 0;
}
</style>
使用第三方组件库
许多流行的 Vue UI 组件库提供了现成的侧边菜单组件,例如 Element UI、Ant Design Vue 等。

<template>
<el-menu
default-active="1"
class="el-menu-vertical"
background-color="#545c64"
text-color="#fff"
active-text-color="#ffd04b">
<el-menu-item index="1">
<i class="el-icon-menu"></i>
<span>首页</span>
</el-menu-item>
<el-menu-item index="2">
<i class="el-icon-document"></i>
<span>文档</span>
</el-menu-item>
</el-menu>
</template>
<script>
import { ElMenu, ElMenuItem } from 'element-plus'
export default {
components: {
ElMenu,
ElMenuItem
}
}
</script>
实现可折叠侧边菜单
通过 Vue 的状态管理可以实现侧边菜单的折叠功能。
<template>
<div class="sidebar" :class="{ 'collapsed': isCollapsed }">
<button @click="toggleCollapse">Toggle</button>
<ul>
<li v-for="item in menuItems" :key="item.path">
<router-link :to="item.path">
<span v-if="!isCollapsed">{{ item.title }}</span>
</router-link>
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
isCollapsed: false,
menuItems: [
{ path: '/home', title: 'Home' },
{ path: '/about', title: 'About' }
]
}
},
methods: {
toggleCollapse() {
this.isCollapsed = !this.isCollapsed
}
}
}
</script>
<style>
.sidebar {
width: 200px;
transition: width 0.3s;
}
.sidebar.collapsed {
width: 50px;
}
</style>
响应式侧边菜单
结合媒体查询和 Vue 的状态管理,可以实现响应式的侧边菜单。
<template>
<div class="sidebar" :class="{ 'mobile-hidden': !showMobileMenu }">
<!-- 菜单内容 -->
</div>
</template>
<script>
export default {
data() {
return {
showMobileMenu: false,
windowWidth: window.innerWidth
}
},
created() {
window.addEventListener('resize', this.handleResize)
},
destroyed() {
window.removeEventListener('resize', this.handleResize)
},
methods: {
handleResize() {
this.windowWidth = window.innerWidth
},
toggleMobileMenu() {
this.showMobileMenu = !this.showMobileMenu
}
},
computed: {
isMobile() {
return this.windowWidth <= 768
}
}
}
</script>
<style>
@media (max-width: 768px) {
.sidebar.mobile-hidden {
display: none;
}
}
</style>
以上方法可以根据具体需求选择使用,或者结合多种方法实现更复杂的功能。






