nuxt-toc
nuxt-toc

Nuxt module for table of contents (TOC) component in Nuxt Content projects

nuxt-toc

npm version npm downloads License CI

Use a Table of Contents for files created with @nuxt/content module. This version is compatible with @nuxt/content v2 and v3.

Full documentation: https://thaikolja.github.io/nuxt-toc/

☀︎ English · 中文 · Deutsch · Español · Français · فارسی

Features

  • Content v2 (queryContent) and v3 (queryCollection)
  • Pass-in :toc (recommended) or optional auto-fetch
  • Nested link depth control
  • Active section highlighting (scroll-spy)
  • Optional smooth scroll + sticky-header offset
  • Stable CSS class/id hooks for theming
  • Accessible list markup

Install

Step 1: Setup

# Adding to existing site
npx nuxi module add nuxt-toc

# Or install manually
npm install nuxt-toc

Step 2: Add module to Nuxt

If you installed nuxt-toc via nuxi module, you can skip this step.

// nuxt.config.ts
export default defineNuxtConfig({
  modules: ['nuxt-toc', '@nuxt/content'],
})

Usage

Prefer passing TOC from your page query. Make sure to use the correct version to match your @nuxt/content version.

<script setup lang="ts">
const route = useRoute()
// @nuxt/content v3:
const { data: page } = await useAsyncData(route.path, () =>
  queryCollection('content').path(route.path).first(),
)

// @nuxt/content v2
// queryContent(route.path).findOne()
</script>

<template>
  <ContentRenderer v-if="page" :value="page" />
  <TableOfContents :toc="page?.body?.toc" />
</template>

Or auto-fetch by path:

<TableOfContents path="/docs/intro" />

Props

PropTypeDefaultDescription
tocToc | nullnullPrefetched TOC (page.body.toc). Skips fetch when set.
pathstring''Auto-fetch path (default: current route).
collectionstring''Content v3 collection (default: nuxtToc.collection / content).
depthnumber2Max nesting depth of the link tree (1 = top-level only).
isSublistShownbooleantrueWhen false, forces depth 1.
isTitleShownWithNoContentbooleanfalseKeep showing the title when there are no links.
titlestring'Table of Contents'Heading text.
scrollSpybooleantrueActive-section highlighting.
rootMarginstring'0px 0px -80% 0px'IntersectionObserver rootMargin.
smoothbooleanfalseSmooth scroll on link click.
scrollOffsetnumber0Scroll offset in px (sticky header).

Module options

Customize nuxt-toc via the following settings (values used here are default values).

export default defineNuxtConfig({
  nuxtToc: {
    collection: 'content',
    depth: 2,
    scrollSpy: true,
    rootMargin: '0px 0px -80% 0px',
    smooth: false,
    scrollOffset: 0,
  },
})

Documentation

To learn more about nuxt-toc and how to use or style it, check out the full documentation. You will find guides, recipes, and more.

Authors

License

This project is licensed under the MIT License.