vue实现小说目录
Vue 实现小说目录的方法
数据准备
需要准备小说章节数据,通常是一个数组,每个元素包含章节标题和内容。数据结构可以如下:
chapters: [
{ title: "第一章", content: "..." },
{ title: "第二章", content: "..." }
]
目录组件
创建一个目录组件,用于显示所有章节标题。使用 v-for 遍历章节数据:

<template>
<div class="catalog">
<ul>
<li v-for="(chapter, index) in chapters" :key="index">
<a @click="selectChapter(index)">{{ chapter.title }}</a>
</li>
</ul>
</div>
</template>
章节选择功能
在目录组件中添加方法,处理章节选择事件,并通知父组件:
methods: {
selectChapter(index) {
this.$emit('chapter-selected', index);
}
}
内容显示组件
创建内容显示组件,接收当前章节索引并显示对应内容:

<template>
<div class="content">
<h2>{{ currentChapter.title }}</h2>
<p>{{ currentChapter.content }}</p>
</div>
</template>
<script>
export default {
props: ['chapters', 'currentIndex'],
computed: {
currentChapter() {
return this.chapters[this.currentIndex];
}
}
}
</script>
父组件整合
在父组件中整合目录和内容显示,管理当前章节索引:
<template>
<div class="reader">
<Catalog :chapters="chapters" @chapter-selected="changeChapter" />
<Content :chapters="chapters" :current-index="currentIndex" />
</div>
</template>
<script>
export default {
data() {
return {
chapters: [...],
currentIndex: 0
}
},
methods: {
changeChapter(index) {
this.currentIndex = index;
}
}
}
</script>
样式优化
添加基础样式改善用户体验:
.catalog {
width: 200px;
float: left;
}
.catalog ul {
list-style: none;
padding: 0;
}
.catalog li a {
cursor: pointer;
padding: 5px;
display: block;
}
.catalog li a:hover {
background-color: #f0f0f0;
}
.content {
margin-left: 220px;
}
进阶功能
- 添加滚动定位:在内容组件中使用
ref和scrollIntoView实现平滑滚动 - 阅读进度保存:使用
localStorage记录当前阅读章节 - 响应式设计:通过媒体查询适配移动设备
这种实现方式保持了组件间的松耦合,便于维护和扩展。目录组件只负责显示和触发事件,内容组件专注展示,父组件管理状态。





