vue实现侧边导航
实现侧边导航的基本结构
使用 Vue 结合 <template> 定义侧边导航的 HTML 结构,通常包含一个 <nav> 或 <aside> 容器,内部通过 v-for 动态渲染导航菜单项。
<template>
<aside class="sidebar">
<nav>
<ul>
<li v-for="item in menuItems" :key="item.id">
<router-link :to="item.path">{{ item.title }}</router-link>
</li>
</ul>
</nav>
</aside>
</template>
定义导航数据
在 Vue 组件的 <script> 中定义导航菜单数据(如 menuItems),通常为一个数组,包含路径(path)和显示文本(title)。
<script>
export default {
data() {
return {
menuItems: [
{ id: 1, title: "首页", path: "/" },
{ id: 2, title: "产品", path: "/products" },
{ id: 3, title: "关于", path: "/about" }
]
};
}
};
</script>
添加样式
通过 <style> 为侧边导航添加基础样式,例如固定宽度、背景色和悬停效果。
<style scoped>
.sidebar {
width: 200px;
background-color: #f0f0f0;
height: 100vh;
position: fixed;
left: 0;
top: 0;
}
.sidebar ul {
list-style: none;
padding: 0;
}
.sidebar li a {
display: block;
padding: 10px;
color: #333;
text-decoration: none;
}
.sidebar li a:hover {
background-color: #ddd;
}
</style>
结合路由
若使用 Vue Router,需确保导航项的 path 与路由配置匹配,并通过 <router-link> 实现路由跳转。
// router.js 示例配置
const routes = [
{ path: "/", component: Home },
{ path: "/products", component: Products },
{ path: "/about", component: About }
];
响应式折叠功能
通过 Vue 的 v-if 或 v-show 控制侧边导航的显示/隐藏,并添加切换按钮。
<template>
<button @click="toggleSidebar">切换导航</button>
<aside class="sidebar" v-show="isSidebarVisible">
<!-- 导航内容 -->
</aside>
</template>
<script>
export default {
data() {
return {
isSidebarVisible: true
};
},
methods: {
toggleSidebar() {
this.isSidebarVisible = !this.isSidebarVisible;
}
}
};
</script>
嵌套子菜单
支持多级菜单时,可通过递归组件或嵌套 v-for 实现。
<template>
<li v-for="item in menuItems" :key="item.id">
<router-link :to="item.path">{{ item.title }}</router-link>
<ul v-if="item.children">
<li v-for="child in item.children" :key="child.id">
<router-link :to="child.path">{{ child.title }}</router-link>
</li>
</ul>
</li>
</template>
使用 UI 库加速开发
若需快速实现复杂侧边导航,可集成第三方 UI 库(如 Element UI、Ant Design Vue)。

<template>
<el-menu :default-active="activeMenu" class="sidebar">
<el-menu-item index="1" @click="navigate('/')">首页</el-menu-item>
<el-submenu index="2">
<template #title>产品</template>
<el-menu-item index="2-1" @click="navigate('/products')">产品列表</el-menu-item>
</el-submenu>
</el-menu>
</template>






