【问题标题】:Why are H1 tags excluded from NuxtJS's Content module's TOC list?为什么从 NuxtJS 的 Content 模块的 TOC 列表中排除 H1 标签?
【发布时间】:2022-01-23 22:37:06
【问题描述】:

我正在导入大量使用大量 H1 (#) 标签的降价内容。在创建 TOC 组件时,我注意到 H1 标签被排除在 @Nuxt/Content 方便地提供的 TOC 数组之外。

事实证明这让我很头疼,我宁愿不编写脚本来更改数百个 MD 文件以将每个标题修改为更深一层,尽管这是一种选择。

我尝试过的事情:

    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);
        });
    },

修改content/parsers/markdown/index.jsgenerateToc函数以在const depth中包含h1

  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
      }
    })
  }

在 Nuxt/Vue 中,文档对象仍未注册要包含在 TOC 中的 h1 标签。有没有人有解决方法或知道如何包含它们?

最后——使用 H1 / # 标签来分隔 Markdown 中的主要部分不是很好的做法吗?

提前致谢!

【问题讨论】:

  • 我想是因为页面应该有一个 H1 指定文档的标题,然后 H2s(及更低)指定该文档的子部分,这些子部分在文档的表格中进行整理内容。
  • @MartinBean 这正是我所怀疑的,但是当我们使用 YAML 块作为文档标题时,我们认为这不会是一个大问题。

标签: vue.js nuxt.js markdown nuxt-content


【解决方案1】:

找错地方了。

我设法通过更改content/lib/utils.js 文件将H1 标签添加到TOC 列表中。

  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
}

在网络上找不到与此问题相关的任何内容,因此希望这对某人有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-07
    • 2022-01-21
    • 2011-04-20
    • 2012-06-23
    • 1970-01-01
    • 1970-01-01
    • 2022-12-31
    • 1970-01-01
    相关资源
    最近更新 更多