vue实现侧导航
Vue 实现侧边导航的方法
使用 Element UI 的 el-menu 组件
安装 Element UI:
npm install element-ui
在 main.js 中引入:
import Vue from 'vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
Vue.use(ElementUI)
在组件中使用:
<el-menu
default-active="1"
class="el-menu-vertical"
background-color="#545c64"
text-color="#fff"
active-text-color="#ffd04b">
<el-submenu index="1">
<template slot="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>
自定义侧边导航组件
创建 Sidebar.vue 组件:

<template>
<div class="sidebar">
<div
v-for="item in menuItems"
:key="item.path"
class="menu-item"
:class="{ active: currentPath === item.path }"
@click="navigateTo(item.path)">
{{ item.title }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
currentPath: '/',
menuItems: [
{ title: '首页', path: '/' },
{ title: '产品', path: '/products' },
{ title: '关于', path: '/about' }
]
}
},
methods: {
navigateTo(path) {
this.$router.push(path)
this.currentPath = path
}
}
}
</script>
<style>
.sidebar {
width: 200px;
background: #2c3e50;
height: 100vh;
color: white;
}
.menu-item {
padding: 15px;
cursor: pointer;
}
.menu-item:hover {
background: #34495e;
}
.menu-item.active {
background: #42b983;
}
</style>
使用 Vue Router 实现导航联动
配置路由:
const routes = [
{ path: '/', component: Home },
{ path: '/products', component: Products },
{ path: '/about', component: About }
]
const router = new VueRouter({
routes
})
在 Sidebar 组件中监听路由变化:
watch: {
'$route'(to) {
this.currentPath = to.path
}
}
响应式侧边导航实现
添加响应式逻辑:

data() {
return {
isCollapsed: false
}
},
methods: {
toggleCollapse() {
this.isCollapsed = !this.isCollapsed
}
}
样式调整:
.sidebar {
transition: width 0.3s;
width: 200px;
}
.sidebar.collapsed {
width: 64px;
}
嵌套路由侧边导航
配置嵌套路由:
const routes = [
{
path: '/dashboard',
component: Dashboard,
children: [
{ path: 'overview', component: Overview },
{ path: 'settings', component: Settings }
]
}
]
导航组件调整:
<el-menu-item index="/dashboard/overview">概览</el-menu-item>
<el-menu-item index="/dashboard/settings">设置</el-menu-item>






