SoFunction
Updated on 2025-04-12

Use Vue directive to implement Markdown rendering and code highlighting

In front-end development, we often need to render Markdown format text into HTML and display it on the page, and we also want to highlight code blocks. Today I will share a piece of code that implements this function through Vue directives.

First, you need to install some dependencies. Execute the following command in your project:

pnpm add  marked @types/marked -D

Next, let’s take a look at the specific code implementation.

existIn the file, we need to register a global Vue directive. The code is as follows:

import { markedDirective } from './path/to/markedDirective'
('marked', markedDirective)

In Vue components, you can usev-markedDirective to render Markdown text and highlight code blocks. The sample code is as follows:

<template>
  <div v-marked:hl="code"></div>
</template>
<script setup lang="ts">
import '/styles/'
import code from '@/config/?raw'
</script>

In the above example code, we importedstyle file and useMarkdown text in the file as an example.

Next, let's take a look at the specific implementation code.

First, we need to importandmarkedThe module, the code is as follows:

import hljs from ''
import { marked } from 'marked'
import { Directive, DirectiveHook, nextTick } from 'vue'

Then, we need to create amarkedThe renderer and set some options, the code is as follows:

const render = new ()
({
  renderer: render,
  gfm: true,
  pedantic: false
})

In the specific implementation of the Vue directive, we define aformatValueFunction, which is used to render Markdown text into HTML and highlight code blocks. The code is as follows:

const formatValue: DirectiveHook = async (el, binding) => {
  const html = marked(binding?.value ?? '')
   = html
  await nextTick()
  if ( === 'hl') {
    const blocks = ('pre code')
    ((block: any) => {
      (block)
    })
  }
}

Finally, we willformatValueFunctions as Vue instructionsmountedandupdatedThe callback function of the hook. In this way, whenever the value bound to the instruction changes, the Markdown text is re-rendered and the code block is highlighted. The code is as follows:

export const markedDirective: Directive = {
  mounted: formatValue,
  updated: formatValue
}

So far, we have completed the implementation of the entire function.

To sum up, through the above code, we can use it in Vue projectv-markedDirective renders Markdown text into HTML and highlights the code blocks therein. This is very useful for displaying documents, blogs and other scenarios.

The above is the detailed content of using Vue instructions to implement Markdown rendering and code highlighting. For more information about Vue Markdown rendering and code highlighting, please pay attention to my other related articles!