当前位置:首页 > VUE

vue实现目录

2026-03-26 19:01:04VUE

Vue 实现目录功能

在 Vue 中实现目录功能通常涉及动态渲染内容标题、监听滚动位置以及高亮当前章节。以下是常见的实现方法:

动态生成目录结构

使用 v-for 循环渲染标题元素,通过 querySelectorAll 获取页面中的标题标签(如 h2/h3):

<template>
  <div class="toc">
    <div v-for="(item, index) in headings" :key="index" 
         :class="{ active: activeIndex === index }"
         @click="scrollTo(item)">
      {{ item.text }}
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      headings: [],
      activeIndex: 0
    }
  },
  mounted() {
    this.initHeadings()
    window.addEventListener('scroll', this.onScroll)
  },
  methods: {
    initHeadings() {
      this.headings = Array.from(document.querySelectorAll('h2, h3'))
        .map(el => ({
          text: el.innerText,
          offsetTop: el.offsetTop
        }))
    },
    scrollTo(item) {
      window.scrollTo({
        top: item.offsetTop,
        behavior: 'smooth'
      })
    },
    onScroll() {
      const scrollPosition = window.scrollY
      this.headings.forEach((item, index) => {
        if (item.offsetTop <= scrollPosition + 100) {
          this.activeIndex = index
        }
      })
    }
  }
}
</script>

使用 IntersectionObserver 优化性能

替代滚动事件监听,减少性能消耗:

methods: {
  setupObserver() {
    const observer = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          const index = this.headings.findIndex(
            h => h.text === entry.target.innerText
          )
          this.activeIndex = index
        }
      })
    }, { threshold: 0.5 })

    document.querySelectorAll('h2, h3').forEach(el => {
      observer.observe(el)
    })
  }
}

嵌套目录实现

对于多级目录(如 h2+h3 层级),需结构化数据:

computed: {
  nestedHeadings() {
    const result = []
    let currentH2 = null

    this.headings.forEach(item => {
      if (item.tagName === 'H2') {
        currentH2 = { ...item, children: [] }
        result.push(currentH2)
      } else if (currentH2) {
        currentH2.children.push(item)
      }
    })

    return result
  }
}

样式优化

添加基础交互样式:

.toc {
  position: fixed;
  max-height: 100vh;
  overflow-y: auto;
}
.toc div {
  padding: 8px 12px;
  cursor: pointer;
}
.toc div.active {
  color: #42b983;
  font-weight: bold;
}
.toc div.children {
  padding-left: 20px;
  font-size: 0.9em;
}

使用第三方库

如需快速实现,可考虑以下库:

  • vue-toc:自动生成目录组件
  • vue-scrollactive:滚动高亮集成
  • vue-affix:固定侧边栏定位

实现时需注意:

vue实现目录

  • beforeDestroy 中移除事件监听
  • 对于 SSR 场景需做客户端判断
  • 动态内容需使用 nextTick 确保 DOM 更新

标签: 目录vue
分享给朋友:

相关文章

vue实现mvc

vue实现mvc

Vue 实现 MVC 模式 Vue 本身是一个 MVVM(Model-View-ViewModel)框架,但可以通过结构调整实现 MVC(Model-View-Controller)模式。以下是具体实…

vue架构实现

vue架构实现

Vue 架构实现核心方案 Vue.js 的架构实现通常围绕模块化、组件化和状态管理展开。以下为常见实现方案: 基于单文件组件(SFC)的模块化 通过 .vue 文件组织模板、脚本和样式: <…

vue vnode实现

vue vnode实现

Vue VNode 实现原理 VNode(Virtual Node)是 Vue 的核心概念之一,用于描述真实 DOM 的轻量级虚拟表示。VNode 的实现涉及以下关键点: VNode 的基本结构 V…

vue 实现打印

vue 实现打印

Vue 实现打印功能的方法 在Vue项目中实现打印功能,可以通过以下几种方式实现: 使用window.print()方法 通过调用浏览器的原生打印API实现基础打印功能,适用于简单内容打印。 //…

vue首页实现

vue首页实现

实现Vue首页的基本步骤 创建一个Vue首页通常涉及项目初始化、页面结构设计、路由配置和组件开发。以下是具体实现方法: 初始化Vue项目 使用Vue CLI或Vite快速搭建项目结构: npm i…

vue实现评分

vue实现评分

Vue 实现评分功能 使用组件库实现 安装 element-ui 或 ant-design-vue 这类 UI 库,它们已经内置了评分组件。 以 element-ui 为例: <templa…