0

我正在导入大量使用大量 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.js generateToc函数以将 h1 包含在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
      }
    })
  }

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

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

提前致谢!

4

1 回答 1

0

找错地方了。

我设法通过更改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
}

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

于 2021-12-22T18:50:05.883 回答