vue 左右联动 + 锚点
时间: 2023-09-06 16:10:12 浏览: 47
实现 vue 左右联动和锚点有多种方法,下面提供一种思路:
1. 在左侧导航栏中使用 v-for 循环渲染出所有锚点,并绑定点击事件。
2. 在右侧内容区域中,使用 v-for 循环渲染出所有内容块。
3. 给内容块设置唯一的 id 值,与左侧导航栏的锚点对应。例如,第一个锚点对应的内容块 id 为 "section-1"。
4. 在点击左侧导航栏的锚点时,通过 $refs 获取对应内容块的 DOM 元素,并调用其 scrollIntoView 方法实现跳转。
5. 在右侧内容区域滚动时,监听滚动事件,计算出当前滚动位置,然后根据位置计算出对应的锚点,并设置其为激活状态。
下面是一个简单的示例代码:
```html
<template>
<div class="container">
<div class="left">
<ul>
<li v-for="(item, index) in sections" :key="index" @click="scrollToSection(index)" :class="{ active: activeSection === index }">{{ item.title }}</li>
</ul>
</div>
<div class="right">
<div v-for="(item, index) in sections" :key="index" :id="'section-' + index">{{ item.content }}</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
sections: [
{
title: 'Section 1',
content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'
},
{
title: 'Section 2',
content: 'Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.'
},
{
title: 'Section 3',
content: 'Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.'
}
],
activeSection: 0
}
},
mounted() {
window.addEventListener('scroll', this.handleScroll)
},
methods: {
scrollToSection(index) {
const section = this.$refs['section-' + index][0]
section.scrollIntoView({ behavior: 'smooth' })
this.activeSection = index
},
handleScroll() {
const sections = this.$el.querySelectorAll('.right > div')
const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
let activeSection = 0
sections.forEach((section, index) => {
const top = section.offsetTop
if (scrollTop >= top - 200) {
activeSection = index
}
})
this.activeSection = activeSection
}
},
beforeDestroy() {
window.removeEventListener('scroll', this.handleScroll)
}
}
</script>
<style>
.container {
display: flex;
}
.left {
width: 200px;
}
.left ul {
list-style: none;
padding: 0;
}
.left li {
cursor: pointer;
padding: 10px;
}
.left li.active {
background-color: #f0f0f0;
}
.right {
flex: 1;
}
.right div {
height: 500px;
margin: 50px 0;
padding: 20px;
border: 1px solid #ccc;
}
</style>
```