当前位置:首页 > VUE

vue监听滚动实现fixed

2026-01-21 10:36:52VUE

监听滚动实现 Fixed 效果

在 Vue 中监听滚动事件并实现 Fixed 效果,可以通过以下方法实现:

vue监听滚动实现fixed

方法一:使用 v-bind:class 动态绑定样式

vue监听滚动实现fixed

<template>
  <div :class="{ 'fixed-header': isFixed }">
    <!-- 内容 -->
  </div>
</template>

<script>
export default {
  data() {
    return {
      isFixed: false
    }
  },
  mounted() {
    window.addEventListener('scroll', this.handleScroll)
  },
  beforeDestroy() {
    window.removeEventListener('scroll', this.handleScroll)
  },
  methods: {
    handleScroll() {
      this.isFixed = window.scrollY > 100 // 100为滚动阈值
    }
  }
}
</script>

<style>
.fixed-header {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 100;
}
</style>

方法二:使用 Vue 指令

<template>
  <div v-fixed>
    <!-- 内容 -->
  </div>
</template>

<script>
export default {
  directives: {
    fixed: {
      inserted(el) {
        window.addEventListener('scroll', () => {
          const shouldFix = window.scrollY > 100
          el.style.position = shouldFix ? 'fixed' : ''
          el.style.top = shouldFix ? '0' : ''
          el.style.left = shouldFix ? '0' : ''
          el.style.width = shouldFix ? '100%' : ''
          el.style.zIndex = shouldFix ? '100' : ''
        })
      }
    }
  }
}
</script>

方法三:使用 Composition API

<template>
  <div :style="headerStyle">
    <!-- 内容 -->
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted } from 'vue'

export default {
  setup() {
    const isFixed = ref(false)

    const handleScroll = () => {
      isFixed.value = window.scrollY > 100
    }

    onMounted(() => {
      window.addEventListener('scroll', handleScroll)
    })

    onUnmounted(() => {
      window.removeEventListener('scroll', handleScroll)
    })

    const headerStyle = computed(() => ({
      position: isFixed.value ? 'fixed' : '',
      top: isFixed.value ? '0' : '',
      left: isFixed.value ? '0' : '',
      width: isFixed.value ? '100%' : '',
      zIndex: isFixed.value ? '100' : ''
    }))

    return { headerStyle }
  }
}
</script>

注意事项

  • 监听滚动事件时,务必在组件销毁前移除事件监听,避免内存泄漏
  • 使用 position: fixed 时,注意可能影响页面布局,可能需要为后续内容添加 margin/padding
  • 对于性能优化,可以考虑使用 requestAnimationFrame 或节流函数优化滚动事件处理

标签: vuefixed
分享给朋友:

相关文章

vue的实现

vue的实现

Vue 的实现原理 Vue 是一个渐进式 JavaScript 框架,其核心实现主要包括响应式系统、虚拟 DOM、模板编译和组件化机制。以下是 Vue 实现的主要技术细节。 响应式系统 Vue 的响…

vue实现hover

vue实现hover

Vue 实现 hover 效果的方法 在 Vue 中实现 hover 效果可以通过多种方式实现,包括使用 CSS、Vue 指令或事件监听。以下是几种常见的方法: 使用 CSS :hover 伪类 通…

vue单选实现

vue单选实现

Vue 单选实现 在 Vue 中实现单选功能可以通过多种方式完成,以下是几种常见的方法: 使用 v-model 绑定单选按钮 通过 v-model 绑定一个变量,可以实现单选效果。当用户选择不同的选…

vue实现pc

vue实现pc

Vue 实现 PC 端应用开发 Vue.js 是一个流行的前端框架,适用于构建 PC 端 Web 应用。以下是关键步骤和最佳实践: 项目初始化 使用 Vue CLI 或 Vite 创建项目:…

vue实现影院

vue实现影院

Vue实现影院功能的基本思路 使用Vue框架开发影院功能需要结合前端组件化开发、状态管理以及后端API交互。以下是关键实现步骤: 影院页面布局设计 影院页面通常分为顶部导航栏、影院列表区域和底部导航…

vue实现发帖

vue实现发帖

使用 Vue 实现发帖功能 前端实现 创建发帖表单组件,包含标题和内容输入框,以及提交按钮。使用 v-model 绑定表单数据。 <template> <div>…