nuxt3使用markdown-it

使用markdown语法记录博客是一个高效的方式,前端加载时需要解析markdown字符串。在nuxt3框架中vue3解析markdown语法可以直接使用markdown-it来解析。

之前在vue2中使用过vue-markdown这样的依赖,但是vue升级后就无法使用了,而markdown-it不受vue版本影响。

<template>
  <div class="wrapper detail" v-loading.fullscreen="loading">
    <div class="content" v-html="result"></div>
  </div>
</template>

<script setup lang="ts">
import MarkdownIt from 'markdown-it'
import hljs from 'highlight.js'
import 'highlight.js/styles/atom-one-dark.css'

const config = useRuntimeConfig()
const post = ref({
      
      content: ''})
const loading = ref(false)

let md: any = new MarkdownIt({
      
      
  html: true,
  linkify: true,
  typographer: true,
  breaks: true,        // Convert '\n' in paragraphs into <br>
  highlight: function (str:any, lang:any) {
      
      
    if (lang && hljs.getLanguage(lang)) {
      
      
      try {
      
      
        return `<pre><code class="language-${ 
        lang} hljs">` +
               hljs.highlight(str, {
      
       language: lang, ignoreIllegals: true }).value +
               '</code></pre>';
      } catch (__) {
      
      }
    }

    return '<pre><code class="language-none hljs">' + md.utils.escapeHtml(str) + '</code></pre>';
  }
})
let result = md.render(post.value.content)

</script>

搭配上highlight.js,很轻松就实现代码块高亮了。

效果:

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/IICOOM/article/details/129931291