使用 Vue 实现左侧浮动菜单跟随页面滚动
实现步骤
- 创建 Vue 项目:使用 Vue CLI 创建一个新的 Vue 项目。
- 设计 HTML 结构:包含一个左侧浮动菜单和一个主要内容区域。
- 编写 CSS 样式:设置菜单的初始样式和滚动时的样式。
- 使用 Vue 的生命周期钩子和事件监听:监听页面滚动事件,根据滚动位置动态改变菜单的样式。
详细代码
vue
<template>
<!-- 整个页面的容器 -->
<div id="app">
<!-- 左侧浮动菜单 -->
<div class="sidebar" :class="{ 'fixed': isFixed }">
<ul>
<!-- 菜单项 -->
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Contact</a></li>
</ul>
</div>
<!-- 主要内容区域 -->
<div class="content">
<!-- 模拟大量内容 -->
<p v-for="i in 50" :key="i">
This is some sample text. This is some sample text. This is some sample text.
</p>
</div>
</div>
</template>
<script>
export default {
data() {
return {
// 用于标记菜单是否固定的状态
isFixed: false,
// 菜单开始固定的滚动阈值
scrollThreshold: 0
};
},
mounted() {
// 获取侧边栏元素
const sidebar = this.$el.querySelector('.sidebar');
// 计算侧边栏距离页面顶部的距离,作为滚动阈值
this.scrollThreshold = sidebar.offsetTop;
// 监听页面滚动事件
window.addEventListener('scroll', this.handleScroll);
},
beforeDestroy() {
// 在组件销毁前移除滚动事件监听,防止内存泄漏
window.removeEventListener('scroll', this.handleScroll);
},
methods: {
handleScroll() {
// 获取当前页面的滚动位置
const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
// 如果滚动位置超过阈值,将 isFixed 设为 true,否则设为 false
this.isFixed = scrollTop >= this.scrollThreshold;
}
}
};
</script>
<style scoped>
/* 整个页面的样式 */
#app {
display: flex;
margin: 0;
padding: 0;
}
/* 左侧浮动菜单的初始样式 */
.sidebar {
width: 200px;
background-color: #f4f4f4;
padding: 20px;
position: relative;
}
/* 菜单固定时的样式 */
.sidebar.fixed {
position: fixed;
top: 0;
}
/* 主要内容区域的样式 */
.content {
flex: 1;
padding: 20px;
}
/* 菜单项的样式 */
.sidebar ul {
list-style-type: none;
padding: 0;
}
.sidebar li {
margin-bottom: 10px;
}
.sidebar a {
text-decoration: none;
color: #333;
}
</style>
代码注释说明
-
HTML 部分:
<div class="sidebar" :class="{ 'fixed': isFixed }">
:侧边栏菜单,根据isFixed
状态动态添加fixed
类。<div class="content">
:主要内容区域,包含大量模拟文本。
-
JavaScript 部分:
data
:定义isFixed
用于标记菜单是否固定,scrollThreshold
用于存储菜单开始固定的滚动阈值。mounted
:在组件挂载后,计算侧边栏距离页面顶部的距离作为滚动阈值,并监听页面滚动事件。beforeDestroy
:在组件销毁前移除滚动事件监听,防止内存泄漏。handleScroll
:处理滚动事件,根据滚动位置更新isFixed
状态。
-
CSS 部分:
.sidebar
:侧边栏菜单的初始样式,使用position: relative
。.sidebar.fixed
:菜单固定时的样式,使用position: fixed
。
使用说明
- 创建项目:使用 Vue CLI 创建一个新的 Vue 项目。
- 替换代码 :将上述代码复制到
src/App.vue
文件中。 - 运行项目 :在终端中运行
npm run serve
启动开发服务器。 - 查看效果 :打开浏览器,访问
http://localhost:8080
,滚动页面,观察左侧浮动菜单的滚动效果。