使用vue2根据element组件写一个右边展开收起的侧边导航栏
时间: 2024-02-25 16:58:49 浏览: 78
基于Vue实现的侧边栏导航组件
5星 · 资源好评率100%
好的,下面是一个使用 Vue2 和 Element 组件库实现的右侧展开收起的侧边导航栏的示例代码:
```html
<template>
<div class="sidebar-container">
<el-button type="primary" icon="el-icon-s-fold" @click="collapseSidebar"></el-button>
<el-menu :collapse="isCollapsed" :default-active="$route.path" class="el-menu-vertical-demo" router>
<el-submenu :index="menu.index" v-for="menu in menus" :key="menu.index">
<template slot="title">
<i :class="menu.icon"></i>
<span slot="title">{{ menu.title }}</span>
</template>
<el-menu-item :index="submenu.index + item.index" v-for="submenu in menu.submenus" :key="submenu.index" :disabled="submenu.disabled" v-if="submenu.show">
<router-link :to="submenu.route">{{ submenu.title }}</router-link>
</el-menu-item>
</el-submenu>
</el-menu>
</div>
</template>
<script>
export default {
data() {
return {
isCollapsed: false, // 导航栏是否展开
menus: [
{
index: '1',
title: '菜单1',
icon: 'el-icon-menu',
submenus: [
{
index: '1-1',
title: '子菜单1-1',
route: '/menu1/submenu1',
disabled: false,
show: true
},
{
index: '1-2',
title: '子菜单1-2',
route: '/menu1/submenu2',
disabled: false,
show: true
}
]
},
{
index: '2',
title: '菜单2',
icon: 'el-icon-menu',
submenus: [
{
index: '2-1',
title: '子菜单2-1',
route: '/menu2/submenu1',
disabled: false,
show: true
},
{
index: '2-2',
title: '子菜单2-2',
route: '/menu2/submenu2',
disabled: false,
show: true
}
]
}
]
}
},
methods: {
collapseSidebar() {
this.isCollapsed = !this.isCollapsed;
}
}
}
</script>
<style>
.sidebar-container {
height: 100%;
background-color: #fff;
overflow: hidden;
position: relative;
}
.el-menu-vertical-demo {
width: 200px;
height: 100%;
position: absolute;
top: 0;
bottom: 0;
transition: all 0.3s;
}
.el-menu-vertical-demo .el-submenu__title {
height: 50px;
line-height: 50px;
font-size: 14px;
}
.el-menu-vertical-demo .el-submenu__title i {
margin-right: 10px;
}
.el-menu-vertical-demo .el-menu-item {
height: 50px;
line-height: 50px;
font-size: 14px;
}
.el-menu-vertical-demo .el-menu-item.is-active,
.el-menu-vertical-demo .el-submenu.is-active > .el-submenu__title {
background-color: #f5f7fa;
color: #409eff;
}
.el-menu-vertical-demo.el-menu--collapse {
width: 60px;
}
.el-menu-vertical-demo.el-menu--collapse .el-submenu__title {
height: 60px;
line-height: 60px;
}
.el-menu-vertical-demo.el-menu--collapse .el-submenu__title i {
margin-right: 0;
font-size: 20px;
}
.el-menu-vertical-demo.el-menu--collapse .el-menu-item {
height: 60px;
line-height: 60px;
font-size: 20px;
}
.el-button {
position: absolute;
top: 20px;
right: 0;
z-index: 999;
}
</style>
```
这段代码实现了一个带有收起按钮的侧边导航栏,当点击收起按钮时,导航栏会从原来的宽度自动收缩到指定宽度,同时菜单项的字体大小也会随之调整。你可以根据自己的需要,修改菜单项的内容和样式。
阅读全文