Vue3 渲染markdown——marked并代码块高亮

6,039 阅读1分钟

技术栈 vue3 ts

1.安装依赖

npm install marked : 用来解析markdown

npm install marked-highlight : 用来代码块高亮

npm install github-markdown-css : 设置markdown样式

npm install highlight.js:语法高亮

2.使用marked

<script lang="ts" setup>

import { ref, shallowRef } from 'vue';
import {getArticleDetails,type ArticleDetailsModel} from '@/API/Home/Article'
import { onMounted } from 'vue';
import {Marked} from 'marked';
import { markedHighlight } from "marked-highlight"
import hljs from 'highlight.js'
//引入markdown样式
import 'highlight.js/styles/atom-one-dark.css' 

const articleDetails=ref()


const marked=new Marked(
  markedHighlight({
    langPrefix: 'hljs language-',
    highlight(code, lang) {
    const language = hljs.getLanguage(lang) ? lang : 'shell'
    return hljs.highlight(code, { language }).value
  }
  })
)



onMounted(async()=>{
  const content=await getArticleDetails(1).then(res=>res.content)

   articleDetails.value= marked.parse(content)
})
</script>


<template>
   <div class="markdown-body">
    <div v-html="articleDetails" class="markdown-body"></div>
  </div>
</template>

  <style scoped lang="less">
   

  </style>
  

3.之后补充一些拓展

未完待续!