vue侧边栏实现
实现 Vue 侧边栏的基本方法
使用 Vue 结合 Vue Router 和组件化思想实现侧边栏。通过动态路由和状态管理控制侧边栏的显示与隐藏。
<template>
<div class="sidebar-container" :class="{ 'collapsed': isCollapsed }">
<div class="sidebar-menu">
<router-link
v-for="item in menuItems"
:key="item.path"
:to="item.path"
class="menu-item"
>
<i :class="item.icon"></i>
<span v-show="!isCollapsed">{{ item.title }}</span>
</router-link>
</div>
<button @click="toggleCollapse" class="collapse-btn">
{{ isCollapsed ? '>' : '<' }}
</button>
</div>
</template>
侧边栏样式设计
通过 CSS 实现侧边栏的过渡动画和响应式布局,确保在不同屏幕尺寸下表现良好。
.sidebar-container {
width: 250px;
height: 100vh;
background-color: #2c3e50;
transition: width 0.3s ease;
position: fixed;
left: 0;
top: 0;
}
.sidebar-container.collapsed {
width: 64px;
}
.menu-item {
display: flex;
align-items: center;
padding: 12px 20px;
color: white;
text-decoration: none;
}
.menu-item i {
margin-right: 10px;
font-size: 20px;
}
.collapse-btn {
position: absolute;
right: -20px;
top: 20px;
width: 20px;
height: 20px;
background: #2c3e50;
border: none;
color: white;
cursor: pointer;
}
动态菜单数据管理
通过 Vuex 或 Pinia 管理侧边栏菜单状态,实现权限控制和动态加载。
import { defineComponent, ref } from 'vue';
export default defineComponent({
setup() {
const isCollapsed = ref(false);
const menuItems = ref([
{ path: '/dashboard', title: 'Dashboard', icon: 'el-icon-menu' },
{ path: '/users', title: 'Users', icon: 'el-icon-user' },
{ path: '/settings', title: 'Settings', icon: 'el-icon-setting' }
]);
const toggleCollapse = () => {
isCollapsed.value = !isCollapsed.value;
};
return { isCollapsed, menuItems, toggleCollapse };
}
});
响应式适配方案
结合媒体查询实现移动端适配,在较小屏幕上自动折叠侧边栏。
@media (max-width: 768px) {
.sidebar-container {
width: 64px;
}
.sidebar-container:not(.collapsed) {
width: 250px;
z-index: 1000;
}
}
与 Vue Router 集成
通过路由守卫和动态路由实现侧边栏菜单与路由的同步。
const routes = [
{
path: '/',
component: Layout,
children: [
{ path: 'dashboard', component: Dashboard },
{ path: 'users', component: Users },
{ path: 'settings', component: Settings }
]
}
];
第三方组件库方案
使用 Element UI 或 Ant Design Vue 等现成组件库快速实现侧边栏。
<template>
<el-menu
:default-active="activeIndex"
class="el-menu-vertical"
:collapse="isCollapse"
>
<el-menu-item index="1">
<i class="el-icon-menu"></i>
<span>Dashboard</span>
</el-menu-item>
</el-menu>
</template>






