1
1
<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 >
3
4
</template >
4
5
5
6
<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 '
8
9
import ' highlight.js/styles/vs2015.min.css'
9
10
import hljs from ' highlight.js'
10
11
@@ -19,45 +20,26 @@ const props = defineProps({
19
20
const message = useMessage () // 消息弹窗
20
21
const { copy } = useClipboard () // 初始化 copy 到粘贴板
21
22
const contentRef = ref ()
22
- const contentHtml = ref <any >() // 渲染的html内容
23
23
const { content } = toRefs (props ) // 将 props 变为引用类型
24
24
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 (__ ) {}
36
32
}
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 ` `
39
34
}
40
- }
41
-
42
- // 配置 marked
43
- marked .use ({
44
- renderer: renderer
45
- })
35
+ });
46
36
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
+ });
56
40
57
41
/** 初始化 **/
58
42
onMounted (async () => {
59
- // 解析转换 markdown
60
- await renderMarkdown (props .content as string )
61
43
// 添加 copy 监听
62
44
contentRef .value .addEventListener (' click' , (e : any ) => {
63
45
if (e .target .id === ' copy' ) {
0 commit comments