vue实现侧边导航
Vue 实现侧边导航的方法
使用 Vue Router 和组件化方式
创建一个独立的侧边导航组件 Sidebar.vue,结合 Vue Router 实现路由跳转。在组件中定义导航菜单项,并通过 router-link 绑定路由路径。
<template>
<div class="sidebar">
<router-link
v-for="item in navItems"
:key="item.path"
:to="item.path"
active-class="active"
>
{{ item.name }}
</router-link>
</div>
</template>
<script>
export default {
data() {
return {
navItems: [
{ path: '/home', name: '首页' },
{ path: '/about', name: '关于' },
{ path: '/contact', name: '联系' }
]
}
}
}
</script>
<style>
.sidebar {
width: 200px;
background-color: #f5f5f5;
}
.active {
font-weight: bold;
color: #42b983;
}
</style>
结合 Element UI 或 Ant Design Vue
使用 UI 框架提供的现成导航组件快速实现。例如 Element UI 的 el-menu 组件:

<template>
<el-menu
router
default-active="/home"
class="sidebar"
>
<el-menu-item index="/home">
<span>首页</span>
</el-menu-item>
<el-menu-item index="/about">
<span>关于</span>
</el-menu-item>
</el-menu>
</template>
<script>
import { ElMenu, ElMenuItem } from 'element-plus'
export default {
components: {
ElMenu,
ElMenuItem
}
}
</script>
动态生成导航菜单
从后端 API 获取导航数据,动态渲染导航菜单:

<template>
<div class="sidebar">
<div
v-for="item in menuItems"
:key="item.id"
@click="navigateTo(item.path)"
>
{{ item.title }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
menuItems: []
}
},
async created() {
const response = await fetch('/api/menus')
this.menuItems = await response.json()
},
methods: {
navigateTo(path) {
this.$router.push(path)
}
}
}
</script>
可折叠的侧边导航
实现可展开/折叠的侧边栏,通过 CSS 过渡效果和状态控制:
<template>
<div
class="sidebar"
:class="{ 'collapsed': isCollapsed }"
>
<button @click="toggleCollapse">
{{ isCollapsed ? '展开' : '折叠' }}
</button>
<div class="menu-items">
<router-link to="/home">首页</router-link>
<router-link to="/about">关于</router-link>
</div>
</div>
</template>
<script>
export default {
data() {
return {
isCollapsed: false
}
},
methods: {
toggleCollapse() {
this.isCollapsed = !this.isCollapsed
}
}
}
</script>
<style>
.sidebar {
width: 200px;
transition: width 0.3s ease;
}
.sidebar.collapsed {
width: 60px;
}
</style>
响应式侧边导航
使用媒体查询或 JavaScript 检测屏幕宽度,自动调整侧边导航显示方式:
<template>
<div
class="sidebar"
:class="{ 'mobile-view': isMobile }"
>
<!-- 导航内容 -->
</div>
</template>
<script>
export default {
data() {
return {
isMobile: false
}
},
mounted() {
this.checkScreenWidth()
window.addEventListener('resize', this.checkScreenWidth)
},
beforeDestroy() {
window.removeEventListener('resize', this.checkScreenWidth)
},
methods: {
checkScreenWidth() {
this.isMobile = window.innerWidth < 768
}
}
}
</script>
<style>
@media (max-width: 768px) {
.sidebar {
width: 100%;
position: fixed;
bottom: 0;
}
}
</style>
实现要点
- 路由集成:确保导航菜单与 Vue Router 集成,实现页面跳转
- 状态管理:复杂场景可使用 Vuex 或 Pinia 管理导航状态
- 样式隔离:使用 scoped CSS 防止样式冲突
- 可访问性:为导航添加适当的 ARIA 属性
- 性能优化:大量菜单项时考虑虚拟滚动
以上方法可根据实际项目需求组合使用或单独采用,实现功能完善且美观的侧边导航。






