【优化】marked 替换成 markdown-it

pull/484/head^2
cherishsince 2024-07-24 21:10:09 +08:00
parent 4d3c5b7eff
commit 8c5aaa8801
1 changed files with 16 additions and 34 deletions

View File

@ -1,10 +1,11 @@
<template>
<div ref="contentRef" class="markdown-view" v-html="contentHtml"></div>
<!-- <div ref="contentRef" class="markdown-view" v-html="contentHtml"></div>-->
<div ref="contentRef" class="markdown-view" v-html="renderedMarkdown"></div>
</template>
<script setup lang="ts">
import { useClipboard } from '@vueuse/core'
import { marked } from 'marked'
import {useClipboard} from '@vueuse/core'
import MarkdownIt from 'markdown-it'
import 'highlight.js/styles/vs2015.min.css'
import hljs from 'highlight.js'
@ -19,45 +20,26 @@ const props = defineProps({
const message = useMessage() //
const { copy } = useClipboard() // copy
const contentRef = ref()
const contentHtml = ref<any>() // html
const { content } = toRefs(props) // props
// https://highlightjs.org/
// markdownmarked
/** marked 渲染器 */
const renderer = {
code(code, language, c) {
let highlightHtml
try {
highlightHtml = hljs.highlight(code, { language: language, ignoreIllegals: true }).value
} catch (e) {
// skip
const md = new MarkdownIt({
highlight: function (str, lang) {
if (lang && hljs.getLanguage(lang)) {
try {
const copyHtml = `<div id="copy" data-copy='${str}' style="position: absolute; right: 10px; top: 5px; color: #fff;cursor: pointer;">复制</div>`
return `<pre style="position: relative;">${copyHtml}<code class="hljs">${hljs.highlight(lang, str, true).value}</code></pre>`
} catch (__) {}
}
const copyHtml = `<div id="copy" data-copy='${code}' style="position: absolute; right: 10px; top: 5px; color: #fff;cursor: pointer;">复制</div>`
return `<pre style="position: relative;">${copyHtml}<code class="hljs">${highlightHtml}</code></pre>`
return ``
}
}
});
// marked
marked.use({
renderer: renderer
})
/** 监听 content 变化 */
watch(content, async (newValue, oldValue) => {
await renderMarkdown(newValue)
})
/** 渲染 markdown */
const renderMarkdown = async (content: string) => {
contentHtml.value = await marked(content)
}
const renderedMarkdown = computed(() => {
return md.render(props.content);
});
/** 初始化 **/
onMounted(async () => {
// markdown
await renderMarkdown(props.content as string)
// copy
contentRef.value.addEventListener('click', (e: any) => {
if (e.target.id === 'copy') {