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

pull/469/head
YunaiV 2024-07-11 09:36:56 +08:00
parent 925d356e41
commit 933628050b
1 changed files with 23 additions and 35 deletions

View File

@ -1,28 +1,36 @@
<template>
<div ref="contentRef" class="markdown-view" v-html="contentHtml"></div>
</template>
<script setup lang="ts">
import {useClipboard} from "@vueuse/core";
import {marked} from 'marked'
import { useClipboard } from '@vueuse/core'
import { marked } from 'marked'
import 'highlight.js/styles/vs2015.min.css'
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 contentHtml = ref<any>() // html
const { content } = toRefs(props) // props
// https://highlightjs.org/
// markdownmarked
// marked
/** marked 渲染器 */
const renderer = {
code(code, language, c) {
let highlightHtml
try {
highlightHtml = hljs.highlight(code, {language: language, ignoreIllegals: true}).value
highlightHtml = hljs.highlight(code, { language: language, ignoreIllegals: true }).value
} catch (e) {
// skip
}
@ -36,50 +44,30 @@ marked.use({
renderer: renderer
})
// html
const contentHtml = ref<any>()
//
const props = defineProps({
content: {
type: String,
required: true
}
})
// props
const { content } = toRefs(props)
// content
/** 监听 content 变化 */
watch(content, async (newValue, oldValue) => {
await renderMarkdown(newValue);
await renderMarkdown(newValue)
})
// markdown
/** 渲染 markdown */
const renderMarkdown = async (content: string) => {
contentHtml.value = await marked(content)
}
//
onMounted(async () => {
/** 初始化 **/
onMounted(async () => {
// markdown
await renderMarkdown(props.content as string);
//
await renderMarkdown(props.content as string)
// copy
contentRef.value.addEventListener('click', (e: any) => {
console.log(e)
if (e.target.id === 'copy') {
copy(e.target?.dataset?.copy)
ElMessage({
message: '复制成功!',
type: 'success'
})
message.success('复制成功!')
}
})
})
</script>
<style lang="scss">
.markdown-view {
font-family: PingFang SC;