当前位置:首页 > VUE

vue监听滚动实现fixed

2026-01-21 10:36:52VUE

监听滚动实现 Fixed 效果

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

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

<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

vue监听滚动实现fixed

<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 组件中定义必要的数据属性: data() { return { searchQuery: '', currentPag…

vue实现slider

vue实现slider

Vue 实现 Slider 组件 使用 Vue 实现 Slider 组件可以通过原生开发或借助第三方库。以下是两种常见方法: 原生实现 Slider 创建一个基础的 Slider 组件,通过 v-m…

vue实现drag

vue实现drag

Vue 实现拖拽功能的方法 在 Vue 中实现拖拽功能可以通过原生 HTML5 的拖拽 API 或第三方库如 vuedraggable 来完成。以下是两种常见方法的实现方式。 使用 HTML5 拖拽…

简单实现vue

简单实现vue

Vue 的基本实现 创建一个简单的 Vue 应用需要引入 Vue 库,并编写基本的模板和数据绑定逻辑。 <!DOCTYPE html> <html lang="en"> &l…

vue实现token

vue实现token

Vue 中实现 Token 认证的方法 在 Vue 中实现 Token 认证通常涉及前端与后端的交互,包括 Token 的获取、存储、发送和刷新等操作。以下是具体实现步骤: 获取 Token 用户登…

vue实现心电图

vue实现心电图

Vue 实现心电图效果 在 Vue 中实现心电图效果通常需要结合 Canvas 或 SVG 进行动态绘图,模拟心电图数据的实时变化。以下是两种实现方式的核心思路和代码示例: 使用 Canvas 绘制…