Skip to content

Commit 8c5aaa8

Browse files
committed
【优化】marked 替换成 markdown-it
1 parent 4d3c5b7 commit 8c5aaa8

File tree

1 file changed

+16
-34
lines changed

1 file changed

+16
-34
lines changed

src/components/MarkdownView/index.vue

Lines changed: 16 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
<template>
2-
<div ref="contentRef" class="markdown-view" v-html="contentHtml"></div>
2+
<!-- <div ref="contentRef" class="markdown-view" v-html="contentHtml"></div>-->
3+
<div ref="contentRef" class="markdown-view" v-html="renderedMarkdown"></div>
34
</template>
45

56
<script setup lang="ts">
6-
import { useClipboard } from '@vueuse/core'
7-
import { marked } from 'marked'
7+
import {useClipboard} from '@vueuse/core'
8+
import MarkdownIt from 'markdown-it'
89
import 'highlight.js/styles/vs2015.min.css'
910
import hljs from 'highlight.js'
1011
@@ -19,45 +20,26 @@ const props = defineProps({
1920
const message = useMessage() // 消息弹窗
2021
const { copy } = useClipboard() // 初始化 copy 到粘贴板
2122
const contentRef = ref()
22-
const contentHtml = ref<any>() // 渲染的html内容
2323
const { content } = toRefs(props) // 将 props 变为引用类型
2424
25-
// 代码高亮:https://highlightjs.org/
26-
// 转换 markdown:marked
27-
28-
/** marked 渲染器 */
29-
const renderer = {
30-
code(code, language, c) {
31-
let highlightHtml
32-
try {
33-
highlightHtml = hljs.highlight(code, { language: language, ignoreIllegals: true }).value
34-
} catch (e) {
35-
// skip
25+
const md = new MarkdownIt({
26+
highlight: function (str, lang) {
27+
if (lang && hljs.getLanguage(lang)) {
28+
try {
29+
const copyHtml = `<div id="copy" data-copy='${str}' style="position: absolute; right: 10px; top: 5px; color: #fff;cursor: pointer;">复制</div>`
30+
return `<pre style="position: relative;">${copyHtml}<code class="hljs">${hljs.highlight(lang, str, true).value}</code></pre>`
31+
} catch (__) {}
3632
}
37-
const copyHtml = `<div id="copy" data-copy='${code}' style="position: absolute; right: 10px; top: 5px; color: #fff;cursor: pointer;">复制</div>`
38-
return `<pre style="position: relative;">${copyHtml}<code class="hljs">${highlightHtml}</code></pre>`
33+
return ``
3934
}
40-
}
41-
42-
// 配置 marked
43-
marked.use({
44-
renderer: renderer
45-
})
35+
});
4636
47-
/** 监听 content 变化 */
48-
watch(content, async (newValue, oldValue) => {
49-
await renderMarkdown(newValue)
50-
})
51-
52-
/** 渲染 markdown */
53-
const renderMarkdown = async (content: string) => {
54-
contentHtml.value = await marked(content)
55-
}
37+
const renderedMarkdown = computed(() => {
38+
return md.render(props.content);
39+
});
5640
5741
/** 初始化 **/
5842
onMounted(async () => {
59-
// 解析转换 markdown
60-
await renderMarkdown(props.content as string)
6143
// 添加 copy 监听
6244
contentRef.value.addEventListener('click', (e: any) => {
6345
if (e.target.id === 'copy') {

0 commit comments

Comments
 (0)