1
-
2
1
<template >
3
2
<div ref =" contentRef" class =" markdown-view" v-html =" contentHtml" ></div >
4
3
</template >
5
4
6
5
<script setup lang="ts">
7
- import {useClipboard } from " @vueuse/core" ;
8
-
9
- import {marked } from ' marked'
6
+ import { useClipboard } from ' @vueuse/core'
7
+ import { marked } from ' marked'
10
8
import ' highlight.js/styles/vs2015.min.css'
11
9
import hljs from ' highlight.js'
12
- import {ref } from " vue" ;
13
10
14
- const {copy} = useClipboard () // 初始化 copy 到粘贴板
11
+ // 定义组件属性
12
+ const props = defineProps ({
13
+ content: {
14
+ type: String ,
15
+ required: true
16
+ }
17
+ })
18
+
19
+ const message = useMessage () // 消息弹窗
20
+ const { copy } = useClipboard () // 初始化 copy 到粘贴板
15
21
const contentRef = ref ()
22
+ const contentHtml = ref <any >() // 渲染的html内容
23
+ const { content } = toRefs (props ) // 将 props 变为引用类型
16
24
17
25
// 代码高亮:https://highlightjs.org/
18
26
// 转换 markdown:marked
19
27
20
- // marked 渲染器
28
+ /** marked 渲染器 */
21
29
const renderer = {
22
30
code(code , language , c ) {
23
31
let highlightHtml
24
32
try {
25
- highlightHtml = hljs .highlight (code , {language: language , ignoreIllegals: true }).value
33
+ highlightHtml = hljs .highlight (code , { language: language , ignoreIllegals: true }).value
26
34
} catch (e ) {
27
35
// skip
28
36
}
@@ -36,50 +44,30 @@ marked.use({
36
44
renderer: renderer
37
45
})
38
46
39
- // 渲染的html内容
40
- const contentHtml = ref <any >()
41
-
42
- // 定义组件属性
43
- const props = defineProps ({
44
- content: {
45
- type: String ,
46
- required: true
47
- }
48
- })
49
-
50
- // 将 props 变为引用类型
51
- const { content } = toRefs (props )
52
-
53
- // 监听 content 变化
47
+ /** 监听 content 变化 */
54
48
watch (content , async (newValue , oldValue ) => {
55
- await renderMarkdown (newValue );
49
+ await renderMarkdown (newValue )
56
50
})
57
51
58
- // 渲染 markdown
52
+ /** 渲染 markdown */
59
53
const renderMarkdown = async (content : string ) => {
60
54
contentHtml .value = await marked (content )
61
55
}
62
56
63
- // 组件挂在时
64
- onMounted (async () => {
57
+ /** 初始化 * */
58
+ onMounted (async () => {
65
59
// 解析转换 markdown
66
- await renderMarkdown (props .content as string );
67
- //
60
+ await renderMarkdown (props .content as string )
68
61
// 添加 copy 监听
69
62
contentRef .value .addEventListener (' click' , (e : any ) => {
70
- console .log (e )
71
63
if (e .target .id === ' copy' ) {
72
64
copy (e .target ?.dataset ?.copy )
73
- ElMessage ({
74
- message: ' 复制成功!' ,
75
- type: ' success'
76
- })
65
+ message .success (' 复制成功!' )
77
66
}
78
67
})
79
68
})
80
69
</script >
81
70
82
-
83
71
<style lang="scss">
84
72
.markdown-view {
85
73
font-family : PingFang SC;
0 commit comments