vue导航栏实现
Vue 导航栏实现方法
基础路由配置
安装 vue-router 并配置路由表,在 router/index.js 中定义路径与组件的映射关系:
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
const routes = [
{ path: '/', name: 'Home', component: Home },
{ path: '/about', name: 'About', component: () => import('../views/About.vue') }
]
const router = createRouter({
history: createWebHistory(),
routes
})
导航组件实现
创建 NavBar.vue 组件,使用 <router-link> 实现导航跳转:
<template>
<nav>
<router-link to="/">首页</router-link>
<router-link to="/about">关于</router-link>
</nav>
</template>
<style scoped>
nav {
display: flex;
gap: 1rem;
padding: 1rem;
}
.router-link-active {
font-weight: bold;
}
</style>
动态高亮当前页
通过 v-bind 绑定动态类名,结合路由的 exact-active-class 属性:
<router-link
to="/about"
active-class="active-link"
exact-active-class="exact-active"
>关于</router-link>
响应式导航栏
添加移动端菜单切换功能,利用 Vue 的响应式数据:
<script setup>
import { ref } from 'vue'
const isMenuOpen = ref(false)
</script>
<template>
<button @click="isMenuOpen = !isMenuOpen">菜单</button>
<nav :class="{ 'show-menu': isMenuOpen }">
<!-- 导航链接 -->
</nav>
</template>
<style>
@media (max-width: 768px) {
nav {
display: none;
}
.show-menu {
display: flex;
flex-direction: column;
}
}
</style>
权限控制导航项
结合 Vuex 或 Pinia 实现权限过滤:
<script setup>
import { useAuthStore } from '@/stores/auth'
const auth = useAuthStore()
</script>
<template>
<router-link v-if="auth.isAdmin" to="/admin">管理</router-link>
</template>
嵌套路由导航
处理多级菜单时,在路由配置中添加 children 字段:
{
path: '/products',
component: ProductsLayout,
children: [
{ path: '', component: ProductList },
{ path: ':id', component: ProductDetail }
]
}
滚动行为控制
在路由配置中添加滚动行为控制,提升用户体验:
const router = createRouter({
scrollBehavior(to) {
if (to.hash) {
return { el: to.hash }
}
return { top: 0 }
}
})






