vue实现章节目录
Vue 实现章节目录的方法
使用动态组件和路由
在 Vue 中可以通过动态组件和路由实现章节目录功能。定义一个目录组件,通过 v-for 遍历章节数据,生成目录列表。结合 Vue Router 的 router-link 实现章节跳转。
<template>
<div class="chapter-list">
<router-link
v-for="chapter in chapters"
:key="chapter.id"
:to="`/chapter/${chapter.id}`"
>
{{ chapter.title }}
</router-link>
</div>
</template>
<script>
export default {
data() {
return {
chapters: [
{ id: 1, title: '第一章' },
{ id: 2, title: '第二章' },
// 更多章节...
]
}
}
}
</script>
嵌套路由实现多级目录
对于多级目录结构,可以使用 Vue Router 的嵌套路由功能。配置路由时定义子路由,对应不同层级的章节。
const routes = [
{
path: '/book',
component: BookLayout,
children: [
{
path: 'chapter/:id',
component: ChapterContent,
children: [
{
path: 'section/:sectionId',
component: SectionContent
}
]
}
]
}
]
滚动定位到当前章节
在章节内容组件中,可以通过 scrollIntoView 方法实现滚动定位到当前阅读位置。
mounted() {
const element = document.getElementById(this.$route.params.sectionId)
if (element) {
element.scrollIntoView({ behavior: 'smooth' })
}
}
使用状态管理保存阅读进度
结合 Vuex 可以保存用户的阅读进度,实现下次继续阅读功能。
// store.js
state: {
readingProgress: {}
},
mutations: {
updateProgress(state, { chapterId, progress }) {
state.readingProgress[chapterId] = progress
}
}
响应式目录高亮
通过监听路由变化,动态高亮当前所在章节。
.router-link-active {
font-weight: bold;
color: #42b983;
}
虚拟滚动优化性能
对于超长章节列表,可以使用虚拟滚动技术优化性能。
<template>
<RecycleScroller
:items="chapters"
:item-size="50"
key-field="id"
>
<template v-slot="{ item }">
<router-link :to="`/chapter/${item.id}`">
{{ item.title }}
</router-link>
</template>
</RecycleScroller>
</template>






