<template>
<div>
<nav>
<ul>
<li><a href="#section1">Section 1</a></li>
<li><a href="#section2">Section 2</a></li>
<li><a href="#section3">Section 3</a></li>
</ul>
</nav>
<section id="section1">
<h2>Section 1</h2>
<p>This is the first section.</p>
</section>
<section id="section2">
<h2>Section 2</h2>
<p>This is the second section.</p>
</section>
<section id="section3">
<h2>Section 3</h2>
<p>This is the third section.</p>
</section>
</div>
</template>
<script>
export default {
name: 'AnchorExample',
mounted() {
// Smooth scroll to anchor when hash changes
window.addEventListener('hashchange', this.scrollToHash);
},
methods: {
scrollToHash() {
const id = window.location.hash.slice(1);
if (id) {
const element = document.getElementById(id);
if (element) {
element.scrollIntoView({ behavior: 'smooth' });
}
}
}
},
beforeDestroy() {
window.removeEventListener('hashchange', this.scrollToHash);
}
};
</script>
<style scoped>
section {
height: 100vh;
margin-bottom: 20px;
}
nav ul {
list-style-type: none;
padding: 0;
}
nav ul li {
display: inline;
margin-right: 10px;
}
</style>
模板部分 (<template>):
<nav>) 包含三个链接,分别指向页面中的不同部分(#section1, #section2, #section3)。<section> 元素,每个元素都有一个唯一的 id 属性,对应导航栏中的链接。脚本部分 (<script>):
mounted 钩子),添加了一个监听器来监听 URL 的 hash 变化 (window.addEventListener('hashchange', this.scrollToHash)).scrollToHash 方法用于平滑滚动到对应的锚点位置。它通过 window.location.hash 获取当前的锚点 ID,并使用 element.scrollIntoView({ behavior: 'smooth' }) 实现平滑滚动。beforeDestroy 钩子),移除监听器以防止内存泄漏。样式部分 (<style scoped>):
section 占据整个视口高度 (height: 100vh),并且导航栏的链接水平排列。上一篇:vue表格
下一篇:electron+vue
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站