【功能优化】全局:优化 Markdown 组件的代码

This commit is contained in:
YunaiV
2024-07-11 09:36:56 +08:00
parent 925d356e41
commit 933628050b

View File

@@ -1,28 +1,36 @@
<template> <template>
<div ref="contentRef" class="markdown-view" v-html="contentHtml"></div> <div ref="contentRef" class="markdown-view" v-html="contentHtml"></div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import {useClipboard} from "@vueuse/core"; import { useClipboard } from '@vueuse/core'
import { marked } from 'marked'
import {marked} from 'marked'
import 'highlight.js/styles/vs2015.min.css' import 'highlight.js/styles/vs2015.min.css'
import hljs from 'highlight.js' import hljs from 'highlight.js'
import {ref} from "vue";
const {copy} = useClipboard() // 初始化 copy 到粘贴板 // 定义组件属性
const props = defineProps({
content: {
type: String,
required: true
}
})
const message = useMessage() // 消息弹窗
const { copy } = useClipboard() // 初始化 copy 到粘贴板
const contentRef = ref() const contentRef = ref()
const contentHtml = ref<any>() // 渲染的html内容
const { content } = toRefs(props) // 将 props 变为引用类型
// 代码高亮https://highlightjs.org/ // 代码高亮https://highlightjs.org/
// 转换 markdownmarked // 转换 markdownmarked
// marked 渲染器 /** marked 渲染器 */
const renderer = { const renderer = {
code(code, language, c) { code(code, language, c) {
let highlightHtml let highlightHtml
try { try {
highlightHtml = hljs.highlight(code, {language: language, ignoreIllegals: true}).value highlightHtml = hljs.highlight(code, { language: language, ignoreIllegals: true }).value
} catch (e) { } catch (e) {
// skip // skip
} }
@@ -36,50 +44,30 @@ marked.use({
renderer: renderer renderer: renderer
}) })
// 渲染的html内容 /** 监听 content 变化 */
const contentHtml = ref<any>()
// 定义组件属性
const props = defineProps({
content: {
type: String,
required: true
}
})
// 将 props 变为引用类型
const { content } = toRefs(props)
// 监听 content 变化
watch(content, async (newValue, oldValue) => { watch(content, async (newValue, oldValue) => {
await renderMarkdown(newValue); await renderMarkdown(newValue)
}) })
// 渲染 markdown /** 渲染 markdown */
const renderMarkdown = async (content: string) => { const renderMarkdown = async (content: string) => {
contentHtml.value = await marked(content) contentHtml.value = await marked(content)
} }
// 组件挂在时 /** 初始化 **/
onMounted(async () => { onMounted(async () => {
// 解析转换 markdown // 解析转换 markdown
await renderMarkdown(props.content as string); await renderMarkdown(props.content as string)
//
// 添加 copy 监听 // 添加 copy 监听
contentRef.value.addEventListener('click', (e: any) => { contentRef.value.addEventListener('click', (e: any) => {
console.log(e)
if (e.target.id === 'copy') { if (e.target.id === 'copy') {
copy(e.target?.dataset?.copy) copy(e.target?.dataset?.copy)
ElMessage({ message.success('复制成功!')
message: '复制成功!',
type: 'success'
})
} }
}) })
}) })
</script> </script>
<style lang="scss"> <style lang="scss">
.markdown-view { .markdown-view {
font-family: PingFang SC; font-family: PingFang SC;