vue实现侧部导航
Vue 实现侧部导航
使用 Element UI 的 el-menu 组件
安装 Element UI:
npm install element-ui
在 main.js 中引入 Element UI:
import Vue from 'vue';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
Vue.use(ElementUI);
在组件中使用 el-menu:

<template>
<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>
</template>
<style>
.el-menu-vertical {
width: 200px;
height: 100vh;
}
</style>
使用 Vue Router 实现导航跳转
配置路由:
const routes = [
{
path: '/option1',
name: 'Option1',
component: () => import('./views/Option1.vue')
},
{
path: '/option2',
name: 'Option2',
component: () => import('./views/Option2.vue')
}
];
在 el-menu 中添加路由链接:

<el-menu-item index="1-1" @click="$router.push('/option1')">选项1</el-menu-item>
<el-menu-item index="1-2" @click="$router.push('/option2')">选项2</el-menu-item>
自定义侧边栏组件
创建 Sidebar.vue 组件:
<template>
<div class="sidebar">
<div v-for="item in menuItems" :key="item.path" class="menu-item" @click="navigateTo(item.path)">
{{ item.title }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
menuItems: [
{ title: '首页', path: '/' },
{ title: '关于', path: '/about' }
]
};
},
methods: {
navigateTo(path) {
this.$router.push(path);
}
}
};
</script>
<style>
.sidebar {
width: 200px;
background-color: #f0f0f0;
height: 100vh;
}
.menu-item {
padding: 12px 20px;
cursor: pointer;
}
.menu-item:hover {
background-color: #e0e0e0;
}
</style>
响应式侧边栏
添加折叠功能:
<template>
<div>
<button @click="isCollapsed = !isCollapsed">切换</button>
<el-menu
:collapse="isCollapsed"
class="el-menu-vertical"
background-color="#545c64"
text-color="#fff"
active-text-color="#ffd04b">
<!-- 菜单项 -->
</el-menu>
</div>
</template>
<script>
export default {
data() {
return {
isCollapsed: false
};
}
};
</script>
动态生成菜单
从 API 获取菜单数据:
<script>
export default {
data() {
return {
menuItems: []
};
},
async created() {
try {
const response = await axios.get('/api/menu');
this.menuItems = response.data;
} catch (error) {
console.error('获取菜单失败', error);
}
}
};
</script>






