vue实现锚点效果
使用 scrollIntoView 方法
通过 ref 获取目标元素,调用 scrollIntoView 方法实现平滑滚动。
<template>
<div>
<button @click="scrollToSection">跳转到目标区域</button>
<div ref="targetSection">这里是目标区域</div>
</div>
</template>
<script>
export default {
methods: {
scrollToSection() {
this.$refs.targetSection.scrollIntoView({ behavior: 'smooth' });
}
}
};
</script>
使用 vue-router 的哈希模式
通过 vue-router 的哈希模式实现页面内锚点跳转。

<template>
<div>
<router-link to="#section1">跳转到 Section 1</router-link>
<div id="section1">Section 1 内容</div>
</div>
</template>
使用 offset 调整滚动位置
当页面有固定导航栏时,可以通过 offset 调整滚动位置,避免内容被遮挡。

<template>
<div>
<button @click="scrollToSection">跳转到目标区域</button>
<div ref="targetSection" style="margin-top: 100px">这里是目标区域</div>
</div>
</template>
<script>
export default {
methods: {
scrollToSection() {
const element = this.$refs.targetSection;
const offset = 100; // 调整偏移量
const bodyRect = document.body.getBoundingClientRect().top;
const elementRect = element.getBoundingClientRect().top;
const elementPosition = elementRect - bodyRect;
const offsetPosition = elementPosition - offset;
window.scrollTo({
top: offsetPosition,
behavior: 'smooth'
});
}
}
};
</script>
使用第三方库 vue-scrollto
安装 vue-scrollto 库,通过指令或方法实现锚点效果。
npm install vue-scrollto
<template>
<div>
<button v-scroll-to="'#target'">跳转到目标区域</button>
<div id="target">这里是目标区域</div>
</div>
</template>
<script>
import VueScrollTo from 'vue-scrollto';
export default {
directives: {
'scroll-to': VueScrollTo
}
};
</script>
动态生成锚点
通过 v-for 动态生成锚点链接和目标区域。
<template>
<div>
<button
v-for="(item, index) in sections"
:key="index"
@click="scrollToSection(index)"
>
跳转到 {{ item.title }}
</button>
<div
v-for="(item, index) in sections"
:key="index"
:ref="`section-${index}`"
>
{{ item.content }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
sections: [
{ title: 'Section 1', content: '内容 1' },
{ title: 'Section 2', content: '内容 2' }
]
};
},
methods: {
scrollToSection(index) {
this.$refs[`section-${index}`][0].scrollIntoView({ behavior: 'smooth' });
}
}
};
</script>






