vue实现小说目录
Vue 实现小说目录的步骤
数据准备
确保有小说章节数据,通常是一个数组,每个元素包含章节标题和内容。例如:
chapters: [
{ title: "第一章", content: "..." },
{ title: "第二章", content: "..." }
]
目录列表渲染
使用 v-for 渲染目录列表,并绑定点击事件跳转章节:
<template>
<div class="catalog">
<ul>
<li v-for="(chapter, index) in chapters" :key="index" @click="goToChapter(index)">
{{ chapter.title }}
</li>
</ul>
</div>
</template>
跳转逻辑实现
在 methods 中定义跳转方法,通过索引切换当前章节:
methods: {
goToChapter(index) {
this.currentChapter = this.chapters[index];
}
}
当前章节高亮
通过动态 class 实现当前选中章节的高亮效果:
<li
v-for="(chapter, index) in chapters"
:class="{ active: currentChapterIndex === index }"
>
{{ chapter.title }}
</li>
样式优化
添加基础样式美化目录列表:
.catalog ul {
list-style: none;
padding: 0;
}
.catalog li {
padding: 8px;
cursor: pointer;
}
.catalog li.active {
background: #eee;
}
滚动定位增强
对于长目录可添加滚动定位功能,确保当前章节可见:
goToChapter(index) {
this.currentChapterIndex = index;
const element = this.$el.querySelectorAll('li')[index];
element.scrollIntoView({ behavior: 'smooth' });
}
响应式设计
通过 CSS 媒体查询适配移动端:
@media (max-width: 768px) {
.catalog {
width: 100%;
}
}
持久化当前阅读进度
使用 localStorage 保存阅读进度:

// 保存进度
localStorage.setItem('lastReadChapter', this.currentChapterIndex);
// 初始化时读取
const savedChapter = localStorage.getItem('lastReadChapter');
if (savedChapter) {
this.currentChapterIndex = Number(savedChapter);
}





