使用 nuxt/content 显示从数据库中获取的 markdown

Use nuxt/content to display markdown fetched from a database

我在我的应用程序中使用 nuxt / content,它工作正常。在应用程序的另一部分,我想从数据库中获取一些降价并显示它。

let mytext = "Some *markdown* fetched from a db here."

<nuxt-content :document="mytext" />

这不起作用,因为我缺少一个解析步骤;当您执行 $content("a_page_title_here").fetch() 时,它会解析获取的文本并将其按结构 json.

呈现给组件

如何使用 $content 解析文本,以便将其传递给组件进行显示?

我敢打赌有办法做到这一点,但该文档不包含描述您可以使用 $content 执行的所有操作的参考部分。

如果有使用底层 Remark 组件的简单方法,我可以做到。

这样不行吗?

const mytext = await this.$content('a_page_title_here').fetch()

可以使用包含Markdown的底层Markdown class from @nuxt/content. Its async toJSON() function takes a filename or string (via gray-matter)解析,解析出一个JSON对象,可以传给<nuxt-content>.document.

要使用默认 rehype 插件初始化 Markdown,请使用 getDefaults() and processMarkdownOptions():

// ~/utils/parseMarkdown.js
import Markdown from '@nuxt/content/parsers/markdown'
import { getDefaults, processMarkdownOptions } from '@nuxt/content/lib/utils'

export async function parseMarkdown(md) {
  const options = getDefaults()
  processMarkdownOptions(options)
  return new Markdown(options.markdown).toJSON(md) // toJSON() is async
}

然后像这样在你的组件中使用它:

<template>
  <nuxt-content :document="page" />
</template>

<script>
import { parseMarkdown } from '~/utils/parseMarkdown'

export default {
  async asyncData({ $axios }) {
    const resp = await $axios.get('https://example.com/page.md')
    const page = await parseMarkdown(resp.data)
    return { page }
  }
}
</script>

demo