vue实现章节目录
实现章节目录的基本思路
在Vue中实现章节目录功能,通常需要结合数据驱动和组件化思想。核心是通过数据管理章节结构,利用递归组件或动态渲染实现目录层级展示。
数据结构设计
建议使用嵌套结构存储章节信息,例如:
chapters: [
{
id: 1,
title: "第一章",
children: [
{
id: 2,
title: "第一节",
children: [...]
}
]
}
]
递归组件实现
创建可递归调用的目录组件:
<template>
<ul>
<li v-for="chapter in chapters" :key="chapter.id">
<a @click="handleClick(chapter)">{{ chapter.title }}</a>
<chapter-list
v-if="chapter.children"
:chapters="chapter.children"
@select="handleSelect"
/>
</li>
</ul>
</template>
<script>
export default {
name: 'ChapterList',
props: ['chapters'],
methods: {
handleSelect(chapter) {
this.$emit('select', chapter)
}
}
}
</script>
滚动定位功能
实现章节跳转时自动滚动到对应内容区域:
methods: {
scrollToChapter(chapterId) {
const el = document.getElementById(`chapter-${chapterId}`)
if (el) {
el.scrollIntoView({ behavior: 'smooth' })
}
}
}
高亮当前章节
通过监听滚动事件判断当前阅读位置:
data() {
return {
activeChapter: null
}
},
mounted() {
window.addEventListener('scroll', this.onScroll)
},
methods: {
onScroll() {
const chapters = document.querySelectorAll('[data-chapter]')
let current
chapters.forEach(chapter => {
const rect = chapter.getBoundingClientRect()
if (rect.top <= 100) {
current = chapter.dataset.chapter
}
})
this.activeChapter = current
}
}
响应式样式处理
为目录添加响应式样式,在小屏幕下可折叠:
.chapter-list {
max-height: 100vh;
overflow-y: auto;
}
@media (max-width: 768px) {
.chapter-list {
position: fixed;
width: 80%;
background: white;
z-index: 100;
}
}
完整组件示例
整合后的完整组件可能包含以下功能点:
- 递归渲染章节树
- 滚动定位
- 当前章节高亮
- 响应式布局
- 展开/折叠控制
可根据实际需求调整实现细节,如添加图标、动画效果等增强用户体验。






