vue 实现顶部导航栏
实现顶部导航栏的基本结构
在Vue中创建顶部导航栏通常使用<nav>元素结合Vue的响应式特性。以下是一个基础模板示例:
<template>
<nav class="navbar">
<div class="navbar-brand">Logo</div>
<ul class="navbar-items">
<li v-for="item in navItems" :key="item.id">
<router-link :to="item.path">{{ item.name }}</router-link>
</li>
</ul>
</nav>
</template>
<script>
export default {
data() {
return {
navItems: [
{ id: 1, name: 'Home', path: '/' },
{ id: 2, name: 'About', path: '/about' },
{ id: 3, name: 'Contact', path: '/contact' }
]
}
}
}
</script>
<style scoped>
.navbar {
display: flex;
justify-content: space-between;
padding: 1rem;
background-color: #333;
color: white;
}
.navbar-items {
display: flex;
list-style: none;
gap: 1rem;
}
.navbar-items a {
color: white;
text-decoration: none;
}
</style>
响应式导航栏实现
对于移动端适配,可以添加汉堡菜单功能:

<template>
<nav class="navbar">
<div class="navbar-brand">Logo</div>
<button @click="toggleMenu" class="hamburger">☰</button>
<ul :class="['navbar-items', { 'active': isMenuOpen }]">
<!-- 导航项内容 -->
</ul>
</nav>
</template>
<script>
export default {
data() {
return {
isMenuOpen: false
}
},
methods: {
toggleMenu() {
this.isMenuOpen = !this.isMenuOpen
}
}
}
</script>
<style scoped>
.hamburger {
display: none;
background: none;
border: none;
color: white;
font-size: 1.5rem;
}
@media (max-width: 768px) {
.hamburger {
display: block;
}
.navbar-items {
display: none;
flex-direction: column;
width: 100%;
}
.navbar-items.active {
display: flex;
}
}
</style>
使用Vue Router的导航守卫
为当前活动路由添加高亮样式:
<template>
<li v-for="item in navItems" :key="item.id">
<router-link
:to="item.path"
:class="{ 'active': $route.path === item.path }"
>
{{ item.name }}
</router-link>
</li>
</template>
<style scoped>
.active {
font-weight: bold;
border-bottom: 2px solid #42b983;
}
</style>
使用UI组件库(如Element UI)
快速实现专业导航栏:

<template>
<el-menu
mode="horizontal"
background-color="#545c64"
text-color="#fff"
active-text-color="#ffd04b"
:default-active="$route.path"
>
<el-menu-item
v-for="item in navItems"
:key="item.id"
:index="item.path"
>
<router-link :to="item.path">{{ item.name }}</router-link>
</el-menu-item>
</el-menu>
</template>
<script>
import { ElMenu, ElMenuItem } from 'element-plus'
export default {
components: {
ElMenu,
ElMenuItem
}
}
</script>
固定定位导航栏
使导航栏始终停留在页面顶部:
.navbar {
position: fixed;
top: 0;
left: 0;
right: 0;
z-index: 1000;
}
注意在页面内容中添加顶部内边距以避免内容被导航栏遮挡:
body {
padding-top: 60px; /* 根据导航栏高度调整 */
}






