当前位置:首页 > 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 项目中实现目录功能,可以通过以下几种方式实现,具体取决于需求和技术栈。 使用 Vue Router 实现路由目录 Vue Router 是 Vue.js 的官方…

vue实现一个系统

vue实现一个系统

Vue 系统实现步骤 项目初始化与配置 使用 Vue CLI 或 Vite 创建项目: npm init vue@latest my-system 选择需要的配置(Router、Pinia 等)。…

vue实现发送值接受值

vue实现发送值接受值

Vue 实现父子组件传值 父组件向子组件传值(props) 父组件通过 v-bind 或简写 : 向子组件传递数据。子组件通过 props 接收数据。 父组件代码: <template&g…

vue实现弹窗

vue实现弹窗

Vue 实现弹窗的常见方法 使用组件化方式封装弹窗 创建一个独立的弹窗组件(如 Modal.vue),通过 v-if 或 v-show 控制显示隐藏: <template> <…

vue实现帖子

vue实现帖子

Vue 实现帖子功能 使用 Vue 实现帖子功能需要结合前端框架和后端数据交互,以下是实现的关键步骤和代码示例。 帖子列表展示 创建帖子列表组件,使用 v-for 渲染帖子数据,通过 axios…

vue实现alert

vue实现alert

实现自定义 Alert 组件 在 Vue 中可以通过组件化方式实现自定义 Alert 弹窗。以下是基于 Vue 3 的实现示例: 组件代码 (Alert.vue) <template>…