2

Suppose, I have a string with markdown contents in it in my database and after fetching that string from the database how can I display it with nuxtjs content module without using md extension? Can anyone show me how to do that?

Istiyak
  • 23
  • 1
  • 3

3 Answers3

4

Given your requirement, you don't have to use nuxt content module just to render some markdown, instead you can use something like @nuxtjs/markdownit

Once this added to your project you can use $md to render markdown in your document with below config

nuxt.config.js

{
  modules: [
    '@nuxtjs/markdownit'
  ],
  markdownit: {
    runtime: true // Support `$md()`
  }
}

page/component.vue

<template>
  <div v-html="$md.render(model)"></div>
</template>

<script>
export default {
  data() {
    return {
      model: '# Hello World!'
    }
  }
}
</script>
UdithIshara
  • 405
  • 3
  • 7
2

Thanks to tony19's answer, I was able to create simple component which renders passed string with Markdown content dynamically. Maybe it will be useful for somebody, too!

./components/MarkdownStringRenderer.vue

<script setup>
import markdownParser from "@nuxt/content/transformers/markdown"

const props = defineProps({
  markdownString: {
    type: String,
    required: true,
  }
});

const record = ref("");

watchEffect(async () => {
  await markdownParser.parse("custom.md", props.markdownString).then((md) => record.value = md);
});
</script>

<template>
  <ContentRendererMarkdown :value="record" v-if="record" />
</template>

Component usage example:

<MarkdownStringRenderer :markdownString="description" />

Markdown will be re-rendered each time description changes.

Hazadus
  • 78
  • 8
0

Thanks to Hazadus' answer above.

Here is how I modified with nuxt3 typescript:

<template>
ContentRendererMarkdown(v-if="record" :value="record")
</template>

<script setup lang="ts">
// @ts-expect-error avoid lint error
import markdownParser from '@nuxt/content/transformers/markdown'

const props = defineProps<{
  markdownString: string
}>()

const record = ref<string>('')

watch(
  () => props.markdownString,
  async () => {
    await markdownParser
      .parse('customId', props.markdownString)
      .then((md: string) => (record.value = md))
  },
)
</script>
Saviah Kao
  • 320
  • 1
  • 5
  • 13