vue实现页面滚动
监听滚动事件
在Vue中可以通过v-on指令或@简写绑定scroll事件到窗口或DOM元素。例如监听窗口滚动:
<template>
<div @scroll="handleScroll">可滚动内容</div>
</template>
<script>
export default {
methods: {
handleScroll(e) {
console.log(e.target.scrollTop)
}
}
}
</script>
使用Vue指令封装滚动行为
通过自定义指令实现复用性更高的滚动逻辑:
Vue.directive('scroll', {
inserted(el, binding) {
el.addEventListener('scroll', () => {
if (el.scrollTop + el.clientHeight >= el.scrollHeight - 10) {
binding.value()
}
})
}
})
使用方式:

<div v-scroll="loadMore" style="height: 300px; overflow-y: auto"></div>
滚动到指定位置
使用原生DOM方法实现精准滚动:
methods: {
scrollToElement() {
const el = document.getElementById('target')
el.scrollIntoView({ behavior: 'smooth' })
},
scrollToTop() {
window.scrollTo({
top: 0,
behavior: 'smooth'
})
}
}
滚动节流优化
为避免频繁触发滚动事件导致性能问题,建议使用节流函数:

import { throttle } from 'lodash'
export default {
mounted() {
window.addEventListener('scroll', throttle(this.handleScroll, 200))
},
beforeDestroy() {
window.removeEventListener('scroll', this.handleScroll)
}
}
使用第三方库
对于复杂滚动需求,可考虑专用库:
vue-scrollto:提供声明式滚动指令vue-virtual-scroller:处理大数据列表的虚拟滚动vuescroll:定制化滚动容器解决方案
安装示例:
npm install vue-scrollto
使用示例:
import VueScrollTo from 'vue-scrollto'
Vue.use(VueScrollTo)
<button v-scroll-to="'#element'">滚动到元素</button>






