vue监听滚动实现fixed
监听滚动实现 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
<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或节流函数优化滚动事件处理







