vue实现书籍目录
实现书籍目录的基本思路
使用Vue实现书籍目录通常需要结合数据绑定、组件化和路由跳转等功能。核心是将目录数据结构化,通过递归组件或列表渲染展示层级关系,并支持点击跳转到对应章节。
数据结构设计
典型的目录数据结构可采用嵌套数组或对象形式,例如:
const chapters = [
{
id: 1,
title: "第一章",
children: [
{ id: 1.1, title: "第一节" },
{ id: 1.2, title: "第二节" }
]
},
{
id: 2,
title: "第二章",
children: [
{
id: 2.1,
title: "第一节",
children: [
{ id: 2.1.1, title: "第一小节" }
]
}
]
}
]
递归组件实现
创建可递归渲染的目录组件:
<template>
<ul>
<li v-for="item in data" :key="item.id">
<span @click="handleClick(item)">{{ item.title }}</span>
<directory-tree
v-if="item.children && item.children.length"
:data="item.children"
/>
</li>
</ul>
</template>
<script>
export default {
name: 'DirectoryTree',
props: ['data'],
methods: {
handleClick(item) {
this.$emit('select', item)
}
}
}
</script>
路由跳转集成
在父组件中集成路由跳转逻辑:
<template>
<div class="book-container">
<directory-tree
:data="chapters"
@select="jumpToChapter"
/>
<router-view/>
</div>
</template>
<script>
import DirectoryTree from './DirectoryTree.vue'
export default {
components: { DirectoryTree },
data() {
return {
chapters: [...] // 目录数据
}
},
methods: {
jumpToChapter(item) {
this.$router.push(`/chapter/${item.id}`)
}
}
}
</script>
样式优化
添加基础样式增强可读性:
ul {
list-style-type: none;
padding-left: 1em;
}
li span {
cursor: pointer;
padding: 0.2em 0;
display: inline-block;
}
li span:hover {
color: #42b983;
text-decoration: underline;
}
动态加载实现
对于大型书籍目录,可考虑动态加载:
async loadChapter(id) {
const res = await fetch(`/api/chapters/${id}`)
this.currentChapter = await res.json()
}
响应式目录高亮
通过路由匹配实现当前章节高亮:
computed: {
activeChapterId() {
return this.$route.params.id
}
}
在模板中添加高亮类绑定:
<span
:class="{ active: item.id === activeChapterId }"
@click="handleClick(item)"
>
{{ item.title }}
</span>
可折叠目录实现
添加折叠功能需扩展组件:

<template>
<ul>
<li v-for="item in data" :key="item.id">
<div class="folder-header" @click="toggle(item)">
<span>{{ item.title }}</span>
<span v-if="hasChildren(item)">{{ isOpen(item) ? '−' : '+' }}</span>
</div>
<directory-tree
v-if="isOpen(item) && hasChildren(item)"
:data="item.children"
/>
</li>
</ul>
</template>






