Vue 3 实现左侧列表点击跳转滚动到右侧对应区域的功能
warning:
这篇文章距离上次修改已过190天,其中的内容可能已经有所变动。
在Vue 3中,你可以使用组合式API实现左侧列表项点击后滚动到右侧对应区域的功能。以下是一个简单的示例:
<template>
<div class="container">
<div class="left-menu">
<ul>
<li v-for="(item, index) in items" :key="index" @click="scrollToAnchor(item.anchor)">
{{ item.label }}
</li>
</ul>
</div>
<div class="right-content">
<div v-for="(item, index) in items" :key="index" :id="item.anchor">
{{ item.content }}
</div>
</div>
</div>
</template>
<script>
import { ref } from 'vue';
export default {
setup() {
const items = ref([
{ label: 'Section 1', anchor: 'section1', content: 'Content for section 1' },
{ label: 'Section 2', anchor: 'section2', content: 'Content for section 2' },
// ...
]);
function scrollToAnchor(anchor) {
const el = document.getElementById(anchor);
if (el) {
el.scrollIntoView({ behavior: 'smooth' });
}
}
return {
items,
scrollToAnchor,
};
},
};
</script>
<style>
.container {
display: flex;
}
.left-menu ul {
list-style-type: none;
padding: 0;
}
.left-menu li {
cursor: pointer;
}
.right-content div {
height: 500px;
margin: 20px 0;
}
</style>
在这个示例中,我们有一个左侧菜单和一个包含不同区域的右侧内容。每个列表项通过点击事件调用scrollToAnchor
函数,并将对应的锚点名称作为参数传递。该函数通过document.getElementById
查找对应id的DOM元素,并使用scrollIntoView
方法平滑滚动到该元素。
确保你的右侧区域的div有唯一的id与左侧列表项的anchor对应,并且你的Vue组件被挂载到一个有足够高度的容器元素中,以便scrollIntoView
能够工作。
评论已关闭