vue实现滚屏
vue实现滚屏的方法
使用原生滚动API
通过window.scrollTo或Element.scrollIntoView实现基础滚动效果。适合简单场景,无需额外依赖。

// 滚动到指定位置
window.scrollTo({
top: 500,
behavior: 'smooth'
});
// 元素滚动到视口
document.getElementById('section').scrollIntoView({
behavior: 'smooth'
});
使用vue-scrollto插件
安装插件后可通过指令或方法触发滚动,支持动画效果和回调函数。

npm install vue-scrollto
// 全局注册
import VueScrollTo from 'vue-scrollto';
Vue.use(VueScrollTo);
// 指令方式
<button v-scroll-to="'#section'">跳转</button>
// 方法调用
this.$scrollTo('#section', 500, {
easing: 'ease-in',
onDone: () => console.log('滚动完成')
});
自定义滚动组件
通过封装requestAnimationFrame实现平滑滚动控制,适合需要高度定制化的场景。
export default {
methods: {
smoothScroll(target, duration) {
const targetElement = document.querySelector(target);
const targetPosition = targetElement.offsetTop;
const startPosition = window.pageYOffset;
let startTime = null;
const animation = (currentTime) => {
if (!startTime) startTime = currentTime;
const timeElapsed = currentTime - startTime;
const run = easeInOutQuad(timeElapsed, startPosition, targetPosition, duration);
window.scrollTo(0, run);
if (timeElapsed < duration) requestAnimationFrame(animation);
};
const easeInOutQuad = (t, b, c, d) => {
t /= d/2;
if (t < 1) return c/2*t*t + b;
t--;
return -c/2 * (t*(t-2) - 1) + b;
};
requestAnimationFrame(animation);
}
}
}
结合路由的滚动行为
在Vue Router中配置scrollBehavior实现页面切换时的定位控制。
const router = new VueRouter({
routes: [...],
scrollBehavior(to, from, savedPosition) {
if (to.hash) {
return {
selector: to.hash,
behavior: 'smooth'
}
}
return savedPosition || { x: 0, y: 0 }
}
});
注意事项
- 移动端需考虑
passive event listeners优化 - 滚动容器非body时需要指定
container参数 - 大量内容滚动时需进行性能测试
- 考虑浏览器兼容性(如Safari对平滑滚动的支持)






