vue实现导航栏切换
使用 Vue 实现导航栏切换
动态绑定 class 实现高亮
通过 v-bind:class 绑定动态类名,根据当前选中项切换样式:
<template>
<div class="nav-bar">
<div
v-for="(item, index) in navItems"
:key="index"
:class="{ 'active': currentIndex === index }"
@click="currentIndex = index"
>
{{ item }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
navItems: ['首页', '产品', '关于', '联系'],
currentIndex: 0
}
}
}
</script>
<style>
.nav-bar div {
padding: 10px 20px;
cursor: pointer;
}
.active {
color: #42b983;
border-bottom: 2px solid #42b983;
}
</style>
使用路由实现导航切换
结合 Vue Router 实现页面级导航切换:
-
安装路由:
npm install vue-router -
配置路由文件:
// router/index.js import { createRouter, createWebHistory } from 'vue-router' import Home from '../views/Home.vue' import Products from '../views/Products.vue'
const routes = [ { path: '/', component: Home }, { path: '/products', component: Products } ]
const router = createRouter({ history: createWebHistory(), routes })
export default router
3. 导航组件实现:
```vue
<template>
<nav>
<router-link to="/">首页</router-link>
<router-link to="/products">产品</router-link>
</nav>
<router-view/>
</template>
<style>
.router-link-active {
color: #42b983;
font-weight: bold;
}
</style>
使用组件状态管理
对于复杂应用,可以使用 Pinia 管理导航状态:
-
安装 Pinia:
npm install pinia -
创建 store:
// stores/navStore.js import { defineStore } from 'pinia'
export const useNavStore = defineStore('nav', { state: () => ({ activeTab: 'home' }), actions: { setActiveTab(tab) { this.activeTab = tab } } })
3. 在组件中使用:
```vue
<template>
<div class="tabs">
<button
v-for="tab in tabs"
:key="tab"
:class="{ active: activeTab === tab }"
@click="setActiveTab(tab)"
>
{{ tab }}
</button>
</div>
</template>
<script setup>
import { useNavStore } from '@/stores/navStore'
import { storeToRefs } from 'pinia'
const navStore = useNavStore()
const { activeTab } = storeToRefs(navStore)
const { setActiveTab } = navStore
const tabs = ['home', 'products', 'contact']
</script>
响应式导航栏实现
添加响应式设计,在小屏幕下显示汉堡菜单:
<template>
<div class="navbar">
<div class="logo">VueNav</div>
<div class="menu-btn" @click="toggleMenu">
<span></span>
<span></span>
<span></span>
</div>
<div class="nav-links" :class="{ 'active': isMenuOpen }">
<a
v-for="(link, index) in links"
:key="index"
@click="selectLink(index)"
:class="{ 'active': activeLink === index }"
>
{{ link }}
</a>
</div>
</div>
</template>
<script>
export default {
data() {
return {
links: ['Home', 'About', 'Services', 'Contact'],
activeLink: 0,
isMenuOpen: false
}
},
methods: {
selectLink(index) {
this.activeLink = index
this.isMenuOpen = false
},
toggleMenu() {
this.isMenuOpen = !this.isMenuOpen
}
}
}
</script>
<style>
/* 添加响应式样式 */
@media (max-width: 768px) {
.nav-links {
display: none;
}
.nav-links.active {
display: flex;
flex-direction: column;
}
}
</style>






