vue实现书籍目录
实现书籍目录的基本思路
在Vue中实现书籍目录功能,可以通过组件化的方式构建。目录通常包含章节标题和嵌套的子章节,需要支持展开/折叠功能。核心是递归组件和动态数据绑定。
数据结构的定义
使用树形结构表示目录层级关系,每个节点包含标题、唯一标识符和子节点数组:
data() {
return {
chapters: [
{
id: 1,
title: "第一章",
children: [
{
id: 11,
title: "第一节",
children: []
}
]
}
]
}
}
递归组件实现
创建ChapterItem组件处理嵌套渲染:
<template>
<div class="chapter">
<div @click="toggle" class="chapter-title">
{{ chapter.title }}
<span v-if="hasChildren">{{ isOpen ? '-' : '+' }}</span>
</div>
<div v-show="isOpen && hasChildren" class="children">
<chapter-item
v-for="child in chapter.children"
:key="child.id"
:chapter="child"
/>
</div>
</div>
</template>
<script>
export default {
name: 'ChapterItem',
props: {
chapter: Object
},
data() {
return {
isOpen: false
}
},
computed: {
hasChildren() {
return this.chapter.children && this.chapter.children.length
}
},
methods: {
toggle() {
this.isOpen = !this.isOpen
}
}
}
</script>
样式设计
添加基础样式增强交互体验:

.chapter {
margin-left: 20px;
cursor: pointer;
}
.chapter-title {
padding: 5px;
border-bottom: 1px solid #eee;
}
.chapter-title:hover {
background-color: #f5f5f5;
}
完整组件集成
在主组件中使用递归组件:
<template>
<div class="book-toc">
<chapter-item
v-for="chapter in chapters"
:key="chapter.id"
:chapter="chapter"
/>
</div>
</template>
<script>
import ChapterItem from './ChapterItem.vue'
export default {
components: { ChapterItem },
data() {
return {
chapters: [...]
}
}
}
</script>
动态高亮当前章节
添加当前活跃章节的高亮效果:

// 在ChapterItem组件中
props: {
activeId: [String, Number]
},
computed: {
isActive() {
return this.chapter.id === this.activeId
}
}
.active {
color: #409eff;
font-weight: bold;
}
滚动定位功能
实现点击目录跳转到对应内容区域:
methods: {
scrollToChapter() {
const el = document.getElementById(`chapter-${this.chapter.id}`)
if (el) el.scrollIntoView({ behavior: 'smooth' })
}
}
响应式设计优化
添加媒体查询适应不同屏幕尺寸:
@media (max-width: 768px) {
.book-toc {
width: 100%;
}
}
性能优化建议
对于大型目录结构,可以考虑:
- 虚拟滚动技术
- 异步加载深层目录
- 使用Vue的keep-alive缓存组件状态






