简体   繁体   中英

Why are H1 tags excluded from NuxtJS's Content module's TOC list?

I am in the process of importing a lot of markdown content which all use a fair amount of H1 (#) tags. While creating a TOC component, I noticed that H1 tags are excluded from the @Nuxt/Content's conveniently provided TOC array.

This is proving to be quite a headache for me, and I would rather not write a script to change hundreds of MD files to modify each heading to be one level deeper, although it is an option.

Things I have tried:

    mounted() {
        this.observer = new IntersectionObserver(entries => {
            entries.forEach(entry => {
                const id = entry.target.getAttribute('id');
                if (entry.isIntersecting) {
                    this.currentlyActiveToc = id;
                }
            });
        }, this.observerOptions);

        // Including h1 explicitly to the function
        document.querySelectorAll('.nuxt-content h1[id], .nuxt-content h2[id], .nuxt-content h3[id]').forEach((section) => {
            this.observer.observe(section);
        });
    },

Modifying content/parsers/markdown/index.js generateToc function to include h1 in const depth

  generateToc (body) {
    const { tocTags } = this.options

    const children = this.flattenNode(body, 2)

    return children.filter(node => tocTags.includes(node.tag)).map((node) => {
      const id = node.props.id

      const depth = ({
        h1: 2,
        h2: 3,
        h3: 4,
        h4: 5,
        b5: 6
      })[node.tag]

      const text = this.flattenNodeText(node)

      return {
        id,
        depth,
        text
      }
    })
  }

In Nuxt/Vue the document object is still not registering h1 tags to be included in the TOC. Does anyone have a workaround or an idea of how to include them?

Lastly -- are using H1 / # tags to separate major sections in markdown not considered good practice?

Thanks in advance!

Was looking in the wrong place.

I managed to add H1 tags to the TOC list by changing the content/lib/utils.js file.

  const { tocDepth } = markdown
  const tocTags = []

  if (tocDepth < 1) {
    logger.info(`content.markdown.tocDepth is set as ${tocDepth}. Table of contents of markdown files will be empty.`)
    return tocTags
  }

  if (tocDepth > 6) {
    logger.info(`content.markdown.tocDepth is set as ${tocDepth}. Table of contents of markdown files will include all the headings.`)
  }


  // CHANGE LINE BELOW FROM i=2 to i=1

  for (let i = 1; i <= tocDepth; i++) {
    tocTags.push(`h${i}`)
  }

  return tocTags
}

Couldn't find anything on the web that related to this question, so hope this helps someone!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM