Commit 8c5aaa88 by cherishsince

【优化】marked 替换成 markdown-it

parent 4d3c5b7e
<template> <template>
<div ref="contentRef" class="markdown-view" v-html="contentHtml"></div> <!-- <div ref="contentRef" class="markdown-view" v-html="contentHtml"></div>-->
<div ref="contentRef" class="markdown-view" v-html="renderedMarkdown"></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 MarkdownIt from 'markdown-it'
import 'highlight.js/styles/vs2015.min.css' import 'highlight.js/styles/vs2015.min.css'
import hljs from 'highlight.js' import hljs from 'highlight.js'
...@@ -19,45 +20,26 @@ const props = defineProps({ ...@@ -19,45 +20,26 @@ const props = defineProps({
const message = useMessage() // 消息弹窗 const message = useMessage() // 消息弹窗
const { copy } = useClipboard() // 初始化 copy 到粘贴板 const { copy } = useClipboard() // 初始化 copy 到粘贴板
const contentRef = ref() const contentRef = ref()
const contentHtml = ref<any>() // 渲染的html内容
const { content } = toRefs(props) // 将 props 变为引用类型 const { content } = toRefs(props) // 将 props 变为引用类型
// 代码高亮:https://highlightjs.org/ const md = new MarkdownIt({
// 转换 markdown:marked highlight: function (str, lang) {
if (lang && hljs.getLanguage(lang)) {
/** marked 渲染器 */
const renderer = {
code(code, language, c) {
let highlightHtml
try { try {
highlightHtml = hljs.highlight(code, { language: language, ignoreIllegals: true }).value const copyHtml = `<div id="copy" data-copy='${str}' style="position: absolute; right: 10px; top: 5px; color: #fff;cursor: pointer;">复制</div>`
} catch (e) { return `<pre style="position: relative;">${copyHtml}<code class="hljs">${hljs.highlight(lang, str, true).value}</code></pre>`
// skip } catch (__) {}
} }
const copyHtml = `<div id="copy" data-copy='${code}' style="position: absolute; right: 10px; top: 5px; color: #fff;cursor: pointer;">复制</div>` return ``
return `<pre style="position: relative;">${copyHtml}<code class="hljs">${highlightHtml}</code></pre>`
} }
} });
// 配置 marked
marked.use({
renderer: renderer
})
/** 监听 content 变化 */ const renderedMarkdown = computed(() => {
watch(content, async (newValue, oldValue) => { return md.render(props.content);
await renderMarkdown(newValue) });
})
/** 渲染 markdown */
const renderMarkdown = async (content: string) => {
contentHtml.value = await marked(content)
}
/** 初始化 **/ /** 初始化 **/
onMounted(async () => { onMounted(async () => {
// 解析转换 markdown
await renderMarkdown(props.content as string)
// 添加 copy 监听 // 添加 copy 监听
contentRef.value.addEventListener('click', (e: any) => { contentRef.value.addEventListener('click', (e: any) => {
if (e.target.id === 'copy') { if (e.target.id === 'copy') {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment