vue实现侧边导航
Vue 侧边导航实现方法
使用 Vue 实现侧边导航可以通过多种方式完成,以下提供几种常见方案:
基于 Element UI 的侧边导航
Element UI 提供了现成的导航组件,适合快速开发:

<template>
<el-menu
:default-active="activeIndex"
class="el-menu-vertical"
@select="handleSelect">
<el-menu-item index="1">首页</el-menu-item>
<el-submenu index="2">
<template #title>产品</template>
<el-menu-item index="2-1">产品列表</el-menu-item>
<el-menu-item index="2-2">产品详情</el-menu-item>
</el-submenu>
<el-menu-item index="3">关于我们</el-menu-item>
</el-menu>
</template>
<script>
export default {
data() {
return {
activeIndex: '1'
}
},
methods: {
handleSelect(key) {
console.log(key)
}
}
}
</script>
<style>
.el-menu-vertical {
height: 100vh;
}
</style>
自定义侧边导航组件
如需完全自定义样式,可以创建自己的导航组件:
<template>
<div class="sidebar">
<div
v-for="item in menuItems"
:key="item.id"
class="menu-item"
:class="{ active: activeItem === item.id }"
@click="selectItem(item)">
{{ item.title }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
activeItem: 1,
menuItems: [
{ id: 1, title: '首页' },
{ id: 2, title: '产品' },
{ id: 3, title: '服务' }
]
}
},
methods: {
selectItem(item) {
this.activeItem = item.id
this.$emit('select', item)
}
}
}
</script>
<style>
.sidebar {
width: 200px;
background-color: #f5f5f5;
height: 100vh;
}
.menu-item {
padding: 12px 20px;
cursor: pointer;
}
.menu-item:hover {
background-color: #e0e0e0;
}
.menu-item.active {
background-color: #2196F3;
color: white;
}
</style>
响应式侧边导航
添加响应式功能,在小屏幕设备上自动隐藏:

<template>
<div>
<button @click="toggleSidebar">菜单</button>
<div class="sidebar" :class="{ 'hidden': !isVisible }">
<!-- 导航内容 -->
</div>
</div>
</template>
<script>
export default {
data() {
return {
isVisible: true
}
},
methods: {
toggleSidebar() {
this.isVisible = !this.isVisible
}
}
}
</script>
<style>
.sidebar {
transition: transform 0.3s ease;
}
.sidebar.hidden {
transform: translateX(-100%);
}
</style>
嵌套路由集成
与 Vue Router 集成实现导航:
// router.js
const routes = [
{
path: '/',
component: Layout,
children: [
{ path: '', component: Home, name: 'home' },
{ path: 'products', component: Products, name: 'products' }
]
}
]
<!-- 导航组件 -->
<router-link
v-for="route in routes"
:key="route.name"
:to="{ name: route.name }">
{{ route.meta.title }}
</router-link>
动画效果增强
为导航添加平滑过渡效果:
.slide-enter-active, .slide-leave-active {
transition: all 0.3s ease;
}
.slide-enter-from, .slide-leave-to {
transform: translateX(-100%);
opacity: 0;
}
实现注意事项
- 考虑导航状态持久化,可使用 localStorage 保存用户选择的导航项
- 对于复杂项目,建议将导航数据抽离为单独配置文件
- 移动端适配时,可结合媒体查询调整导航样式
- 无障碍访问需确保导航元素有适当的 ARIA 属性
以上方案可根据实际项目需求组合使用或单独采用,Element UI 方案适合快速开发,自定义方案则提供更大灵活性。






