vue实现标题导航
Vue 实现标题导航的方法
在 Vue 中实现标题导航通常涉及动态生成导航菜单或根据页面内容自动生成标题锚点。以下是几种常见的实现方式:
使用 Vue Router 实现导航菜单
通过 Vue Router 的路由配置,可以动态生成导航菜单。路由配置中可以包含标题信息,用于渲染导航栏。
// router.js
const routes = [
{
path: '/home',
name: 'Home',
component: Home,
meta: { title: '首页' }
},
{
path: '/about',
name: 'About',
component: About,
meta: { title: '关于我们' }
}
]
在导航组件中遍历路由生成菜单:

<template>
<nav>
<router-link
v-for="route in $router.options.routes"
:key="route.path"
:to="route.path"
>
{{ route.meta.title }}
</router-link>
</nav>
</template>
自动生成标题锚点导航
对于长文档页面,可以自动提取标题生成锚点导航:
// 在 mounted 钩子中提取 h2 标题
mounted() {
const titles = document.querySelectorAll('h2')
this.navItems = Array.from(titles).map(title => ({
id: title.id || title.textContent.toLowerCase().replace(/\s+/g, '-'),
text: title.textContent
}))
}
<template>
<div class="article-container">
<div class="content">
<h2 id="section1">第一部分</h2>
<!-- 内容 -->
<h2 id="section2">第二部分</h2>
<!-- 内容 -->
</div>
<div class="nav-sidebar">
<a
v-for="item in navItems"
:key="item.id"
:href="`#${item.id}`"
>
{{ item.text }}
</a>
</div>
</div>
</template>
使用第三方库
对于更复杂的需求,可以使用专门库如 vue-scrollactive 实现滚动导航:

import VueScrollactive from 'vue-scrollactive'
Vue.use(VueScrollactive)
<template>
<scrollactive>
<a href="#section1" class="scrollactive-item">Section 1</a>
<a href="#section2" class="scrollactive-item">Section 2</a>
</scrollactive>
</template>
响应式导航栏实现
对于移动端友好的响应式导航栏:
<template>
<nav>
<div class="menu-toggle" @click="isOpen = !isOpen">
<span></span>
<span></span>
<span></span>
</div>
<ul :class="{ 'open': isOpen }">
<li v-for="item in navItems" :key="item.path">
<router-link :to="item.path">{{ item.title }}</router-link>
</li>
</ul>
</nav>
</template>
<script>
export default {
data() {
return {
isOpen: false,
navItems: [
{ path: '/', title: '首页' },
{ path: '/about', title: '关于' }
]
}
}
}
</script>
<style>
/* 响应式样式 */
@media (max-width: 768px) {
ul {
display: none;
}
ul.open {
display: block;
}
}
</style>
动态高亮当前导航项
根据当前路由高亮对应的导航项:
computed: {
currentRoute() {
return this.$route.path
}
}
<template>
<nav>
<router-link
v-for="item in navItems"
:key="item.path"
:to="item.path"
:class="{ 'active': currentRoute === item.path }"
>
{{ item.title }}
</router-link>
</nav>
</template>
以上方法可以根据具体需求选择或组合使用,实现不同复杂度的标题导航功能。






