vue实现小说目录
实现小说目录的基本思路
使用Vue实现小说目录功能,主要涉及数据管理、列表渲染和交互逻辑。目录通常以章节列表形式展示,支持点击跳转对应章节内容。
数据结构设计
目录数据建议采用数组形式存储,每个章节包含标题和标识符(如章节ID或锚点)。示例数据结构如下:
chapters: [
{ id: 'chapter1', title: '第一章 序幕' },
{ id: 'chapter2', title: '第二章 初遇' },
// 更多章节...
]
目录列表渲染
使用v-for指令渲染章节列表,并为每个条目添加点击事件:
<template>
<div class="catalog-container">
<ul class="chapter-list">
<li
v-for="chapter in chapters"
:key="chapter.id"
@click="goToChapter(chapter.id)"
>
{{ chapter.title }}
</li>
</ul>
</div>
</template>
跳转功能实现
实现章节跳转逻辑,可采用以下方式之一:

锚点跳转方式
methods: {
goToChapter(chapterId) {
const element = document.getElementById(chapterId);
if (element) element.scrollIntoView({ behavior: 'smooth' });
}
}
路由跳转方式(适合SPA)

methods: {
goToChapter(chapterId) {
this.$router.push({ path: `/novel/${this.novelId}/${chapterId}` });
}
}
样式优化
为目录添加基础样式提升用户体验:
.catalog-container {
width: 250px;
position: fixed;
left: 0;
top: 0;
height: 100vh;
overflow-y: auto;
background: #f5f5f5;
}
.chapter-list {
list-style: none;
padding: 0;
}
.chapter-list li {
padding: 12px 20px;
cursor: pointer;
border-bottom: 1px solid #eee;
}
.chapter-list li:hover {
background-color: #e9e9e9;
}
当前章节高亮
添加当前章节标识功能,通过动态class实现:
<li
v-for="chapter in chapters"
:class="{ active: currentChapter === chapter.id }"
>
{{ chapter.title }}
</li>
data() {
return {
currentChapter: ''
}
},
methods: {
goToChapter(chapterId) {
this.currentChapter = chapterId;
// 跳转逻辑...
}
}
.active {
color: #1890ff;
font-weight: bold;
background-color: #e6f7ff;
}
响应式处理
针对移动端添加响应式设计,可通过侧边栏折叠功能优化空间利用:
<button @click="showCatalog = !showCatalog">目录</button>
<div class="catalog-container" v-show="showCatalog">
<!-- 目录内容 -->
</div>
data() {
return {
showCatalog: false
}
}






