vue实现左侧导航
Vue 实现左侧导航的方法
使用 Vue 实现左侧导航通常需要结合 Vue Router 和组件化思想。以下是一个完整的实现方案:
创建导航组件
新建一个 Sidebar.vue 组件作为左侧导航栏:
<template>
<div class="sidebar">
<div v-for="item in menuItems" :key="item.path">
<router-link :to="item.path">{{ item.title }}</router-link>
</div>
</div>
</template>
<script>
export default {
data() {
return {
menuItems: [
{ path: '/home', title: '首页' },
{ path: '/about', title: '关于我们' },
{ path: '/contact', title: '联系我们' }
]
}
}
}
</script>
<style scoped>
.sidebar {
width: 200px;
background-color: #f5f5f5;
padding: 20px;
height: 100vh;
}
</style>
配置路由
在 router/index.js 中配置路由:

import Vue from 'vue'
import Router from 'vue-router'
import Home from '../views/Home.vue'
import About from '../views/About.vue'
import Contact from '../views/Contact.vue'
Vue.use(Router)
export default new Router({
routes: [
{ path: '/home', component: Home },
{ path: '/about', component: About },
{ path: '/contact', component: Contact },
{ path: '*', redirect: '/home' }
]
})
在主布局中使用
在 App.vue 中使用导航组件:
<template>
<div id="app">
<Sidebar />
<router-view />
</div>
</template>
<script>
import Sidebar from './components/Sidebar.vue'
export default {
components: {
Sidebar
}
}
</script>
<style>
#app {
display: flex;
}
</style>
添加交互效果
为导航项添加激活状态样式:

<template>
<router-link
:to="item.path"
active-class="active"
exact-active-class="exact-active"
>
{{ item.title }}
</router-link>
</template>
<style scoped>
.active {
color: #42b983;
font-weight: bold;
}
</style>
使用嵌套路由
对于多级导航菜单:
// router/index.js
{
path: '/products',
component: Products,
children: [
{ path: 'list', component: ProductList },
{ path: 'detail/:id', component: ProductDetail }
]
}
<!-- Sidebar.vue -->
<div v-for="item in menuItems" :key="item.path">
<router-link v-if="!item.children" :to="item.path">
{{ item.title }}
</router-link>
<div v-else>
<div>{{ item.title }}</div>
<router-link
v-for="child in item.children"
:key="child.path"
:to="item.path + '/' + child.path"
>
{{ child.title }}
</router-link>
</div>
</div>
响应式处理
添加响应式处理,在小屏幕下隐藏导航:
<template>
<div class="sidebar" :class="{ 'hidden': !isVisible }">
<!-- 导航内容 -->
</div>
<button @click="toggleSidebar">切换导航</button>
</template>
<script>
export default {
data() {
return {
isVisible: true
}
},
methods: {
toggleSidebar() {
this.isVisible = !this.isVisible
}
}
}
</script>
<style>
.sidebar.hidden {
transform: translateX(-100%);
}
</style>






