vue实现滚动效果
Vue 实现滚动效果的方法
使用原生滚动方法
通过 Vue 的 ref 获取 DOM 元素,调用原生 scrollTo 或 scrollIntoView 方法实现滚动。
<template>
<div ref="scrollContainer">
<div v-for="item in items" :key="item.id">{{ item.text }}</div>
</div>
<button @click="scrollToBottom">滚动到底部</button>
</template>
<script>
export default {
data() {
return {
items: [...Array(20).keys()].map(i => ({ id: i, text: `Item ${i}` }))
}
},
methods: {
scrollToBottom() {
const container = this.$refs.scrollContainer
container.scrollTo({
top: container.scrollHeight,
behavior: 'smooth'
})
}
}
}
</script>
使用第三方库 vue-scrollto
安装 vue-scrollto 库提供更便捷的滚动功能,支持动画和多种配置。
npm install vue-scrollto
<template>
<div id="app">
<button v-scroll-to="'#section'">滚动到区域</button>
<div style="height: 1000px"></div>
<div id="section">目标区域</div>
</div>
</template>
<script>
import VueScrollTo from 'vue-scrollto'
export default {
directives: {
'scroll-to': VueScrollTo
}
}
</script>
监听滚动事件
通过 @scroll 监听滚动事件,实现自定义滚动逻辑如无限加载。
<template>
<div class="scroll-container" @scroll="handleScroll">
<!-- 内容 -->
</div>
</template>
<script>
export default {
methods: {
handleScroll(e) {
const { scrollTop, clientHeight, scrollHeight } = e.target
if (scrollHeight - (scrollTop + clientHeight) < 50) {
this.loadMore()
}
}
}
}
</script>
使用 CSS 平滑滚动
通过 CSS 的 scroll-behavior 属性实现简单平滑滚动,无需 JavaScript。
<template>
<div class="scroll-container">
<a href="#section1">Section 1</a>
<div id="section1" style="height: 100vh"></div>
</div>
</template>
<style>
.scroll-container {
scroll-behavior: smooth;
}
</style>
动态锚点滚动
结合 Vue Router 实现路由跳转时的锚点滚动。
// router.js
const router = new VueRouter({
scrollBehavior(to) {
if (to.hash) {
return {
selector: to.hash,
behavior: 'smooth'
}
}
}
})
每种方法适用于不同场景,原生方法适合简单需求,vue-scrollto 适合复杂动画,CSS 方案最轻量,路由集成适合单页应用。







