vue滚动实现
Vue 滚动实现方法
使用原生滚动
通过监听滚动事件实现滚动效果,适用于简单场景。
export default {
mounted() {
window.addEventListener('scroll', this.handleScroll)
},
methods: {
handleScroll() {
console.log(window.scrollY)
}
},
beforeDestroy() {
window.removeEventListener('scroll', this.handleScroll)
}
}
使用 CSS 平滑滚动
通过 CSS 属性实现平滑滚动效果,无需 JavaScript。
html {
scroll-behavior: smooth;
}
使用第三方库
引入 vue-scrollto 等第三方库实现高级滚动功能。
安装:
npm install vue-scrollto
使用:
import VueScrollTo from 'vue-scrollto'
Vue.use(VueScrollTo)
// 在方法中调用
this.$scrollTo('#target', 500, { easing: 'ease-in-out' })
自定义指令实现滚动
创建自定义指令实现元素滚动控制。
Vue.directive('scroll', {
inserted: function(el, binding) {
el.addEventListener('scroll', binding.value)
},
unbind: function(el, binding) {
el.removeEventListener('scroll', binding.value)
}
})
虚拟滚动优化性能
对于大数据列表,使用 vue-virtual-scroller 实现高性能滚动。
安装:
npm install vue-virtual-scroller
使用:
<template>
<RecycleScroller
class="scroller"
:items="items"
:item-size="50"
key-field="id"
v-slot="{ item }"
>
<div class="item">
{{ item.name }}
</div>
</RecycleScroller>
</template>
滚动到指定位置
通过 ref 获取元素位置并滚动。
scrollToElement() {
const el = this.$refs.targetElement
el.scrollIntoView({ behavior: 'smooth' })
}
滚动加载更多
实现无限滚动加载功能。
{
data() {
return {
isLoading: false,
page: 1
}
},
methods: {
handleScroll() {
const bottomOfWindow =
document.documentElement.scrollTop + window.innerHeight >=
document.documentElement.offsetHeight - 100
if (bottomOfWindow && !this.isLoading) {
this.loadMore()
}
},
loadMore() {
this.isLoading = true
// 加载数据逻辑
}
}
}
滚动节流优化
对滚动事件进行节流处理,提升性能。

import { throttle } from 'lodash'
export default {
methods: {
handleScroll: throttle(function() {
// 滚动逻辑
}, 200)
}
}






