直接上代码
<template>
<div>
<nav>
<ul>
<li v-for="item in list">
<a @click="scrollTo('#' + item)">{{ item }}</a>
</li>
</ul>
</nav>
<section id="我">
<h2>Section 10</h2>
</section>
<section id="你">
<h2>Section 223</h2>
</section>
<section id="他">
<h2>Section 3</h2>
</section>
</div>
</template>
<script setup>
import { ref } from "vue";
let list = ref(["我", "你", "他"]);
const scrollTo = (selector) => {
console.log(selector);
const element = document.querySelector(selector);
if (element) {
element.scrollIntoView({ behavior: "smooth" });
}
};
</script>
<style>
a {
color: blue;
cursor: pointer;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
nav {
background-color: #f5f5f5;
padding: 10px 0;
}
nav ul {
display: flex;
list-style: none;
justify-content: center;
}
nav li {
margin: 0 10px;
}
section {
padding: 50px 0;
height: 800px;
}
h2 {
text-align: center;
}
</style>
id最好改成英文字母,不要用汉字,这里的behavior:smooth同样在滚动条事件时有比较大的用处,是为平滑的滚动效果,而不是太过生硬的直接跳转