首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么H1标记被排除在NuxtJS的内容模块的TOC列表之外?

为什么H1标记被排除在NuxtJS的内容模块的TOC列表之外?
EN

Stack Overflow用户
提问于 2021-12-22 18:21:28
回答 1查看 151关注 0票数 0

我正在导入大量的标记内容,这些内容都使用了相当数量的H1 (#)标记。在创建TOC组件时,我注意到H1标记被排除在@Nuxt/Content的方便提供的TOC数组中。

事实证明,这对我来说是一个相当令人头疼的问题,我宁愿不写一个脚本来修改数百个MD文件,将每个标题修改为一个更深的层次,尽管这是一个选项。

我尝试过的事情:

代码语言:javascript
复制
    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函数以在const depth中包含h1

代码语言:javascript
复制
  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中,document对象仍然没有注册要包含在TOC中的h1标记。有没有人有一个解决办法或如何包括他们的想法?

最后--使用H1 / #标记分隔标记中的主要部分不是很好的做法吗?

提前感谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-12-22 18:50:05

找错地方了。

通过更改H1文件,我成功地将content/lib/utils.js标记添加到TOC列表中。

代码语言:javascript
复制
  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
}

在网上找不到任何与这个问题相关的东西,所以希望这能帮到别人!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70453533

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档