vue 实现平滑滚动
使用 scroll-behavior 属性
在 Vue 项目中,可以通过 CSS 的 scroll-behavior 属性实现平滑滚动。在全局样式文件或组件样式中添加以下代码:
html {
scroll-behavior: smooth;
}
这种方法适用于页面内的锚点跳转,但无法自定义滚动速度或动画效果。
使用 Vue Router 的 scrollBehavior
在 Vue Router 中可以通过 scrollBehavior 方法实现路由切换时的平滑滚动。在路由配置文件中添加以下代码:
const router = new VueRouter({
routes,
scrollBehavior(to, from, savedPosition) {
if (to.hash) {
return {
selector: to.hash,
behavior: 'smooth'
}
}
return { x: 0, y: 0, behavior: 'smooth' }
}
})
这种方式支持锚点跳转和页面顶部滚动,behavior: 'smooth' 启用了平滑滚动效果。
使用 window.scrollTo API
对于需要编程控制的滚动,可以使用 window.scrollTo 方法:
window.scrollTo({
top: 0,
behavior: 'smooth'
})
或者滚动到特定元素位置:

const element = document.getElementById('target')
element.scrollIntoView({ behavior: 'smooth' })
使用第三方库
如果需要更复杂的滚动效果,可以考虑以下第三方库:
-
vue-scrollto
安装:npm install vue-scrollto使用:
import VueScrollTo from 'vue-scrollto' Vue.use(VueScrollTo)示例:

<button v-scroll-to="'#target'">Scroll to Target</button> -
smooth-scroll
安装:npm install smooth-scroll使用:
import SmoothScroll from 'smooth-scroll' const scroll = new SmoothScroll('a[href*="#"]')
自定义滚动动画
对于完全自定义的滚动效果,可以使用 requestAnimationFrame 实现:
function smoothScrollTo(targetY, duration = 1000) {
const startY = window.pageYOffset
const distance = targetY - startY
let startTime = null
function animation(currentTime) {
if (!startTime) startTime = currentTime
const timeElapsed = currentTime - startTime
const progress = Math.min(timeElapsed / duration, 1)
window.scrollTo(0, startY + distance * easeInOutQuad(progress))
if (timeElapsed < duration) requestAnimationFrame(animation)
}
function easeInOutQuad(t) {
return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t
}
requestAnimationFrame(animation)
}
调用方式:
smoothScrollTo(500) // 滚动到Y轴500px位置






