vue实现侧导航
Vue 实现侧边导航
使用 Vue 实现侧边导航可以通过多种方式完成,以下是一种常见的实现方法,结合 Vue Router 和动态组件。
基础结构
创建侧边导航栏的基本结构,通常使用 <ul> 和 <li> 标签组织导航项。
<template>
<div class="sidebar">
<ul>
<li v-for="item in navItems" :key="item.path">
<router-link :to="item.path">{{ item.name }}</router-link>
</li>
</ul>
</div>
</template>
数据驱动导航项
通过数据驱动的方式定义导航项,便于动态管理和扩展。

<script>
export default {
data() {
return {
navItems: [
{ name: '首页', path: '/' },
{ name: '关于', path: '/about' },
{ name: '联系', path: '/contact' }
]
}
}
}
</script>
样式设计
为侧边导航添加基础样式,确保布局美观。
<style>
.sidebar {
width: 200px;
background-color: #f4f4f4;
height: 100vh;
padding: 20px;
}
.sidebar ul {
list-style: none;
padding: 0;
}
.sidebar li {
margin-bottom: 10px;
}
.sidebar a {
text-decoration: none;
color: #333;
}
.sidebar a:hover {
color: #42b983;
}
</style>
结合 Vue Router
确保 Vue Router 已配置,导航项的路由路径与路由配置匹配。

import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from './views/Home.vue'
import About from './views/About.vue'
import Contact from './views/Contact.vue'
Vue.use(VueRouter)
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About },
{ path: '/contact', component: Contact }
]
const router = new VueRouter({
routes
})
export default router
动态高亮当前路由
通过 Vue Router 的 $route 对象动态高亮当前选中的导航项。
<template>
<div class="sidebar">
<ul>
<li v-for="item in navItems" :key="item.path">
<router-link
:to="item.path"
:class="{ 'active': $route.path === item.path }"
>
{{ item.name }}
</router-link>
</li>
</ul>
</div>
</template>
.active {
color: #42b983;
font-weight: bold;
}
响应式设计
通过媒体查询或 Vue 的响应式特性,实现侧边导航在不同屏幕尺寸下的显示效果。
@media (max-width: 768px) {
.sidebar {
width: 100%;
height: auto;
}
}
使用组件库加速开发
如果需要快速实现,可以借助组件库如 Element UI 或 Ant Design Vue。
<template>
<el-menu
default-active="/"
class="el-menu-vertical"
router
>
<el-menu-item index="/">
<span>首页</span>
</el-menu-item>
<el-menu-item index="/about">
<span>关于</span>
</el-menu-item>
</el-menu>
</template>
以上方法可以根据实际需求进行调整和扩展,确保侧边导航功能完善且用户体验良好。






