vue 实现目录
Vue 实现目录功能
在 Vue 中实现目录功能通常涉及动态生成目录结构,并根据页面内容自动更新目录项。以下是几种常见的实现方法:
使用 vue-router 生成路由目录
通过 vue-router 的 routes 配置自动生成目录结构,适用于单页面应用(SPA):

// router.js
const routes = [
{ path: '/', name: 'Home', component: Home },
{ path: '/about', name: 'About', component: About },
{ path: '/contact', name: 'Contact', component: Contact }
]
const router = new VueRouter({ routes })
// 目录组件
<template>
<ul>
<li v-for="route in $router.options.routes" :key="route.path">
<router-link :to="route.path">{{ route.name }}</router-link>
</li>
</ul>
</template>
基于页面标题生成目录
通过解析页面中的标题标签(如 h1、h2)动态生成目录:

<template>
<div>
<div ref="content">
<h2>Section 1</h2>
<h3>Subsection 1.1</h3>
<h2>Section 2</h2>
</div>
<ul>
<li v-for="(item, index) in toc" :key="index">
<a :href="'#' + item.id">{{ item.text }}</a>
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return { toc: [] }
},
mounted() {
this.generateToc()
},
methods: {
generateToc() {
const headings = this.$refs.content.querySelectorAll('h2, h3')
this.toc = Array.from(headings).map(heading => ({
id: heading.textContent.toLowerCase().replace(/\s+/g, '-'),
text: heading.textContent
}))
}
}
}
</script>
使用第三方库
借助现成的 Vue 目录库快速实现功能,例如 vue-toc:
npm install vue-toc
<template>
<vue-toc :content="content" :options="options" />
</template>
<script>
import VueToc from 'vue-toc'
export default {
components: { VueToc },
data() {
return {
content: '<h2>Title</h2><p>Content</p>',
options: {
headings: ['h2', 'h3'],
smoothScroll: true
}
}
}
}
</script>
动态目录与滚动联动
实现目录高亮随页面滚动变化:
<template>
<div>
<div class="content" ref="content">
<!-- 内容区 -->
</div>
<div class="toc">
<ul>
<li
v-for="(item, index) in toc"
:key="index"
:class="{ active: activeIndex === index }"
@click="scrollTo(index)"
>
{{ item.text }}
</li>
</ul>
</div>
</div>
</template>
<script>
export default {
data() {
return {
toc: [],
activeIndex: 0
}
},
mounted() {
this.generateToc()
window.addEventListener('scroll', this.onScroll)
},
methods: {
scrollTo(index) {
const target = document.getElementById(this.toc[index].id)
target.scrollIntoView({ behavior: 'smooth' })
},
onScroll() {
// 计算当前激活的目录项
}
}
}
</script>
注意事项
- 如果目录项需要跳转到页面内锚点,确保目标元素有
id属性 - 对于服务端渲染(SSR)场景,需在
mounted生命周期后操作 DOM - 复杂项目可考虑将目录数据通过 Vuex 管理实现跨组件共享
- 移动端需注意目录的响应式布局和交互体验
以上方法可根据实际需求组合使用或调整实现细节。






