vue侧边栏的实现
Vue 侧边栏实现方法
基础布局与组件结构
使用 Vue 3 的 Composition API 结合 <router-link> 实现路由导航侧边栏。以下是一个典型的结构:
<template>
<div class="sidebar">
<div class="logo">Your Logo</div>
<ul class="nav-items">
<li v-for="item in menuItems" :key="item.path">
<router-link :to="item.path">{{ item.title }}</router-link>
</li>
</ul>
</div>
</template>
<script setup>
const menuItems = [
{ path: '/dashboard', title: 'Dashboard' },
{ path: '/users', title: 'Users' },
{ path: '/settings', title: 'Settings' }
]
</script>
<style scoped>
.sidebar {
width: 250px;
height: 100vh;
background: #2c3e50;
color: white;
}
.nav-items a {
color: white;
text-decoration: none;
display: block;
padding: 10px;
}
.router-link-active {
background: #34495e;
}
</style>
动态折叠功能
通过 Vue 的响应式数据控制侧边栏展开/折叠状态:
<script setup>
import { ref } from 'vue'
const isCollapsed = ref(false)
const toggleSidebar = () => isCollapsed.value = !isCollapsed.value
</script>
<template>
<div class="sidebar" :class="{ 'collapsed': isCollapsed }">
<button @click="toggleSidebar">☰</button>
<!-- 其他内容 -->
</div>
</template>
<style>
.sidebar.collapsed {
width: 60px;
}
.sidebar.collapsed .nav-text {
display: none;
}
</style>
嵌套路由支持
结合 Vue Router 的嵌套路由配置:
// router.js
const routes = [
{
path: '/',
component: Layout,
children: [
{ path: '', component: Dashboard },
{ path: 'users', component: Users }
]
}
]
权限控制实现
根据用户角色过滤菜单项:
<script setup>
import { computed } from 'vue'
import { useUserStore } from '@/stores/user'
const userStore = useUserStore()
const allMenuItems = [
{ path: '/admin', title: 'Admin', role: 'admin' },
{ path: '/reports', title: 'Reports', role: 'user' }
]
const menuItems = computed(() =>
allMenuItems.filter(item =>
!item.role || userStore.roles.includes(item.role)
)
)
</script>
动画效果增强
使用 Vue 的过渡组件实现平滑动画:
<template>
<transition name="slide">
<div class="sidebar" v-if="isVisible">
<!-- 内容 -->
</div>
</transition>
</template>
<style>
.slide-enter-active, .slide-leave-active {
transition: transform 0.3s ease;
}
.slide-enter-from, .slide-leave-to {
transform: translateX(-100%);
}
</style>
响应式适配
通过媒体查询实现移动端适配:
@media (max-width: 768px) {
.sidebar {
position: fixed;
z-index: 100;
transform: translateX(-100%);
}
.sidebar.open {
transform: translateX(0);
}
}
状态管理集成
与 Pinia 状态管理结合实现全局状态:

// stores/sidebar.js
export const useSidebarStore = defineStore('sidebar', {
state: () => ({ isOpen: true }),
actions: {
toggle() { this.isOpen = !this.isOpen }
}
})






