vue3固定菜单栏
时间: 2025-05-22 10:01:18 浏览: 13
### 创建 Vue3 吸顶导航菜单栏
在 Vue3 项目中实现吸顶效果的导航菜单栏可以通过多种方式完成,以下是详细的解决方案。
#### 使用自定义组件和动态类名控制
为了实现吸顶效果,可以在滚动页面时检测当前窗口的垂直滚动位置,并根据条件动态添加 CSS 类名以触发样式变化。这种方法的核心在于监听 `scroll` 事件并更新数据绑定的状态。
1. **创建吸顶导航组件**
新建文件路径为 `src/layout/components/header-sticky.vue` 的组件[^1]。
```vue
<template>
<div class="app-header-sticky" :class="{ 'is-show': isSticky }">
<!-- 导航内容 -->
<nav>这里是导航条</nav>
</div>
</template>
<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
const isSticky = ref(false)
const handleScroll = () => {
isSticky.value = window.scrollY > 78 // 当滚动超过78px时设置为true
}
onMounted(() => {
window.addEventListener('scroll', handleScroll)
})
onUnmounted(() => {
window.removeEventListener('scroll', handleScroll)
})
</script>
<style scoped>
.app-header-sticky {
position: relative;
transition: all 0.3s ease-in-out;
}
.app-header-sticky.is-show {
position: fixed;
top: 0;
width: 100%;
background-color: white;
z-index: 999;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
</style>
```
2. **引入吸顶导航组件**
将上述组件引入到布局页或首页中,例如 `src/views/layout/index.vue` 文件中。
```vue
<template>
<header-sticky />
<main>
页面主要内容区域
</main>
</template>
<script setup>
import HeaderSticky from '@/layout/components/header-sticky.vue'
</script>
```
---
#### 利用第三方库简化开发流程
如果希望减少手动处理逻辑的工作量,可以借助 [@vueuse/core](https://github.com/vueuse/vueuse) 提供的方法快速实现吸顶功能。
1. **安装依赖包**
需要先安装 `@vueuse/core` 插件:
```bash
npm install @vueuse/core
```
2. **使用 `useScroll` 方法**
在组件内部调用 `useScroll` 来获取滚动状态,并将其与 DOM 绑定。
```vue
<template>
<div class="app-header-sticky" :class="{ show: y > 78 }">
<nav>这里是导航条</nav>
</div>
</template>
<script setup>
import { useScroll } from '@vueuse/core'
const { y } = useScroll(window) // 获取垂直方向上的滚动距离
</script>
<style scoped>
.app-header-sticky {
position: relative;
transition: all 0.3s ease-in-out;
}
.app-header-sticky.show {
position: fixed;
top: 0;
width: 100%;
background-color: white;
z-index: 999;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
</style>
```
此处通过 `y > 78` 动态切换类名为 `.show` 的状态,从而实现吸顶效果[^3]。
---
#### 结合路由高亮功能
对于更复杂的场景,比如需要支持不同页面间导航项的激活状态,则可结合 `vue-router` 路由参数来管理导航链接的选中状态[^2]。
```javascript
<router-link to="/" active-class="active">Home</router-link>
<router-link to="/about" active-class="active">About</router-link>
```
CSS 样式如下:
```css
.active {
color: red;
}
```
这样即可轻松实现点击跳转的同时自动标记对应选项为活动状态。
---
### 总结
以上两种方案分别适用于不同的需求层次:一种是完全自主掌控的方式;另一种则是利用成熟的工具链加速开发过程。开发者可以根据实际项目的复杂度和技术栈偏好选择适合自己的实现策略。
阅读全文
相关推荐

















