vue实现目录索引
Vue 实现目录索引的方法
在 Vue 中实现目录索引可以通过动态生成锚点链接或结合路由实现。以下是几种常见方法:
使用 v-for 动态生成目录
通过遍历内容中的标题(如 h2、h3),生成目录列表并绑定点击事件跳转至对应位置。
<template>
<div>
<div class="toc">
<ul>
<li v-for="(item, index) in headings" :key="index">
<a @click="scrollTo(item.id)">{{ item.text }}</a>
</li>
</ul>
</div>
<div class="content" ref="content">
<h2 id="section1">Section 1</h2>
<p>Content...</p>
<h2 id="section2">Section 2</h2>
<p>Content...</p>
</div>
</div>
</template>
<script>
export default {
data() {
return {
headings: [
{ id: 'section1', text: 'Section 1' },
{ id: 'section2', text: 'Section 2' }
]
};
},
methods: {
scrollTo(id) {
const element = document.getElementById(id);
if (element) {
element.scrollIntoView({ behavior: 'smooth' });
}
}
}
};
</script>
结合 Vue Router 的哈希模式
如果使用 Vue Router,可以通过哈希路由实现目录跳转。路由配置中启用 hash 模式,目录链接直接使用 # 锚点。

// router.js
const routes = [
{ path: '/', component: Home },
{ path: '/#section1', component: Home },
{ path: '/#section2', component: Home }
];
自动提取标题生成目录
通过 mounted 钩子动态抓取页面中的标题元素(如 h2),生成目录结构。
export default {
data() {
return {
headings: []
};
},
mounted() {
const elements = this.$el.querySelectorAll('h2, h3');
this.headings = Array.from(elements).map(el => ({
id: el.id,
text: el.innerText
}));
}
};
使用第三方库
如需更复杂功能(如高亮当前阅读位置),可使用以下库:

- vue-scrollactive:自动高亮当前滚动位置的目录项。
- vue-toc:自动根据标题生成目录树。
安装示例:
npm install vue-scrollactive
使用方式:
<scrollactive>
<a v-for="item in headings" :href="'#' + item.id" class="scrollactive-item">
{{ item.text }}
</a>
</scrollactive>
样式优化建议
为目录添加样式以提升交互体验:
.toc {
position: fixed;
top: 20px;
left: 20px;
}
.toc a {
cursor: pointer;
color: #333;
}
.toc a:hover {
text-decoration: underline;
}
通过以上方法,可以灵活实现 Vue 中的目录索引功能,适用于文档、博客等长内容页面。






