vue 实现锚点滚动
vue 实现锚点滚动的方法
使用原生 scrollIntoView 方法
在 Vue 中可以通过 ref 获取目标 DOM 元素,调用 scrollIntoView 实现平滑滚动。该方法支持配置滚动行为(平滑/瞬间)。
<template>
<button @click="scrollToSection">滚动到目标区域</button>
<div ref="targetSection">这里是目标内容</div>
</template>
<script>
export default {
methods: {
scrollToSection() {
this.$refs.targetSection.scrollIntoView({
behavior: 'smooth'
});
}
}
}
</script>
通过路由 hash 实现
适用于通过 URL 哈希值跳转的场景,结合 vue-router 的滚动行为配置:
// router.js
const router = new VueRouter({
routes: [...],
scrollBehavior(to) {
if (to.hash) {
return {
selector: to.hash,
behavior: 'smooth'
}
}
}
})
页面中使用常规锚点链接:
<a href="#section-id">跳转</a>
<div id="section-id">目标区域</div>
使用第三方库
若需要更复杂的滚动控制(如偏移量),可引入 vue-scrollto 库:
npm install vue-scrollto
import VueScrollTo from 'vue-scrollto'
Vue.use(VueScrollTo)
// 使用指令
<button v-scroll-to="'#target'">滚动</button>
<div id="target">内容</div>
// 或通过方法调用
this.$scrollTo('#target', 500, {
offset: -50,
easing: 'ease-in'
})
自定义滚动函数
需要精确控制滚动位置时,可手动计算位置并使用 window.scrollTo:
scrollToElement(selector) {
const el = document.querySelector(selector)
const top = el.getBoundingClientRect().top + window.pageYOffset
window.scrollTo({
top: top - 100, // 向上偏移100px
behavior: 'smooth'
})
}
注意事项
- 移动端需检查浏览器对
scrollIntoView的兼容性 - 滚动容器非
window时需获取对应容器的scrollTop - 平滑滚动效果在 Safari 中可能需要 polyfill
- 带固定头部时需计算偏移量避免遮挡







