[Vuejs]-How to render Markdown field in Vue3?

0👍

This is how it works. First install marked and DOMPurify libraries:

npm i marked dompurify

Then set them up in your Vue3 component:

<script setup>
import {reactive} from "vue";
import marked from 'marked';
import DOMPurify from 'dompurify';

const state = reactive({
    content: ""
})

state.content = DOMPurify.sanitize(marked(YOUR_MARKDOWN));

</script>

Then render it in your template:

  <div v-html="state.content"></div>

The DOMPurify library is supposed to sanitize the html and thus making the usage of v-html safe.

Oh, and if you experience the pesky devtools warnings:

DevTools failed to load source map: Could not load content for http://localhost:3000/js/purify.js.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE

that are caused by DOMPurify, I found it easiest to just block them by:

  1. going into devtools settings (clicking on the gear symbol in Chrome Devtools) and
  2. disable Javascript source maps and CSS source maps

Leave a comment