vue实现文档目录
Vue 实现文档目录的方法
使用动态组件与路由
在 Vue 项目中,可以通过动态组件和路由结合实现文档目录功能。创建一个目录组件,根据路由动态加载对应的文档内容。
<template>
<div>
<ul>
<li v-for="item in menuItems" :key="item.path">
<router-link :to="item.path">{{ item.title }}</router-link>
</li>
</ul>
<router-view></router-view>
</div>
</template>
<script>
export default {
data() {
return {
menuItems: [
{ title: '第一章', path: '/chapter1' },
{ title: '第二章', path: '/chapter2' }
]
}
}
}
</script>
基于 Markdown 的目录生成
如果文档内容为 Markdown 格式,可以使用 markdown-it 和 markdown-it-toc-done-right 插件自动生成目录。
import MarkdownIt from 'markdown-it'
import markdownItTocDoneRight from 'markdown-it-toc-done-right'
const md = new MarkdownIt().use(markdownItTocDoneRight)
const html = md.render(markdownContent)
滚动定位与高亮
通过监听滚动事件,实现目录高亮当前阅读的章节。使用 IntersectionObserver API 检测元素是否在视口中。
mounted() {
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
this.activeId = entry.target.id
}
})
}, { threshold: 0.5 })
document.querySelectorAll('h2, h3').forEach((heading) => {
observer.observe(heading)
})
}
响应式目录折叠
对于移动端或小屏幕设备,可以实现可折叠的目录菜单,提升用户体验。
<template>
<div>
<button @click="toggleMenu">目录</button>
<ul v-show="isMenuOpen">
<li v-for="item in items" :key="item.id">
<a @click="scrollTo(item.id)">{{ item.title }}</a>
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
isMenuOpen: false
}
},
methods: {
toggleMenu() {
this.isMenuOpen = !this.isMenuOpen
},
scrollTo(id) {
document.getElementById(id).scrollIntoView({ behavior: 'smooth' })
}
}
}
</script>
目录数据与文档同步
将目录数据与文档内容分离管理,通过 API 或静态文件加载目录结构,便于维护和更新。
created() {
fetch('/api/toc')
.then(response => response.json())
.then(data => {
this.tocItems = data
})
}
以上方法可以根据具体需求组合使用,实现灵活且功能完善的文档目录系统。







