Search code examples
vue.jsmermaid

Mermaid support in Nuxt Vue content


I'm trying to add mermaid support in my Vue application Followed the steps as suggested here

You can view the demo here

Mermaid.vue

<template>
    <div class="mermaid" v-if="show">
        <slot></slot>
    </div>
</template>

<script setup>

let show = ref(false);

const { $mermaid } = useNuxtApp()

onMounted( async() => {
  show.value = true
  $mermaid().initialize({ startOnLoad: true })
  await nextTick()
  $mermaid().init();
})

</script>

And config

import mermaid from 'mermaid';

export default defineNuxtPlugin((nuxtApp) => {
  nuxtApp.provide('mermaid', () => mermaid);
});

However the mermaid block was rendering as a code block instead of a graph.


Solution

  • I see just from the demo that you don't have a working mermaid.vue component. Copying from the working example from the same github thread you linked:

    Mermaid.vue

    <template>
      <pre ref="el" :style="{ display: rendered ? 'block' : 'none' }">
        <slot />
      </pre>
    </template>
    
    <script setup>
    const slot = useSlots()
    const el = ref(null)
    const rendered = ref(false)
    
    async function render() {
      if (!el.value) {
        return
      }
      if (el.value.querySelector('svg')) {
        // Already rendered
        return
      }
    
      // Iterate children to remove comments
      for (const child of el.value.childNodes) {
        if (child.nodeType === Node.COMMENT_NODE) {
          el.value.removeChild(child)
        }
      }
      const { default: mermaid } = await import("mermaid")
      el.value.classList.add('mermaid')
      rendered.value = true
      await mermaid.run({ nodes: [el.value] })
    }
    
    onMounted(() => {
      render()
    })
    </script>
    
    <style>
    .mermaid rect {
      stroke: #6195ff !important;
      fill: #fff !important;
    }
    
    .mermaid .current-doc.node .label {
      color: #fff !important;
    }
    
    .mermaid line {
      stroke: #6195ff !important;
    }
    
    [data-theme="dark"] .mermaid .flowchart-link {
      stroke: #fff !important;
    }
    
    [data-theme="dark"] .mermaid .messageText {
      fill: #fff !important;
    }
    
    [data-theme="dark"] .mermaid marker {
      fill: #fff !important;
      color: #fff !important;
    }
    
    [data-theme="dark"] .mermaid line {
      stroke: #fff !important;
    }
    </style>
    

    Alos, use <mermaid> tag in your .md file

    <mermaid>
    graph TD;
        A-->B;
        A-->C;
        B-->D;
        C-->D;
    </mermaid>
    

    Stackblitz example