关于前端:nuxt3使用markdownit

6次阅读

共计 982 个字符,预计需要花费 3 分钟才能阅读完成。

应用 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,很轻松就实现代码块高亮了。

成果:

正文完
 0