Skip to content

Commit 9336280

Browse files
committed
【功能优化】全局:优化 Markdown 组件的代码
1 parent 925d356 commit 9336280

File tree

1 file changed

+23
-35
lines changed

1 file changed

+23
-35
lines changed

src/components/MarkdownView/index.vue

Lines changed: 23 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,36 @@
1-
21
<template>
32
<div ref="contentRef" class="markdown-view" v-html="contentHtml"></div>
43
</template>
54

65
<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'
108
import 'highlight.js/styles/vs2015.min.css'
119
import hljs from 'highlight.js'
12-
import {ref} from "vue";
1310
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 到粘贴板
1521
const contentRef = ref()
22+
const contentHtml = ref<any>() // 渲染的html内容
23+
const { content } = toRefs(props) // 将 props 变为引用类型
1624
1725
// 代码高亮:https://highlightjs.org/
1826
// 转换 markdown:marked
1927
20-
// marked 渲染器
28+
/** marked 渲染器 */
2129
const renderer = {
2230
code(code, language, c) {
2331
let highlightHtml
2432
try {
25-
highlightHtml = hljs.highlight(code, {language: language, ignoreIllegals: true}).value
33+
highlightHtml = hljs.highlight(code, { language: language, ignoreIllegals: true }).value
2634
} catch (e) {
2735
// skip
2836
}
@@ -36,50 +44,30 @@ marked.use({
3644
renderer: renderer
3745
})
3846
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 变化 */
5448
watch(content, async (newValue, oldValue) => {
55-
await renderMarkdown(newValue);
49+
await renderMarkdown(newValue)
5650
})
5751
58-
// 渲染 markdown
52+
/** 渲染 markdown */
5953
const renderMarkdown = async (content: string) => {
6054
contentHtml.value = await marked(content)
6155
}
6256
63-
// 组件挂在时
64-
onMounted(async () => {
57+
/** 初始化 **/
58+
onMounted(async () => {
6559
// 解析转换 markdown
66-
await renderMarkdown(props.content as string);
67-
//
60+
await renderMarkdown(props.content as string)
6861
// 添加 copy 监听
6962
contentRef.value.addEventListener('click', (e: any) => {
70-
console.log(e)
7163
if (e.target.id === 'copy') {
7264
copy(e.target?.dataset?.copy)
73-
ElMessage({
74-
message: '复制成功!',
75-
type: 'success'
76-
})
65+
message.success('复制成功!')
7766
}
7867
})
7968
})
8069
</script>
8170

82-
8371
<style lang="scss">
8472
.markdown-view {
8573
font-family: PingFang SC;

0 commit comments

Comments
 (0)