处理DeepSeek返回的markdown文本
处理DeepSeek返回的markdown文本
markdown预览组件,支持公式显示,支持uniapp。
相关依赖
markdown-it
markdown-it-mathjax
markdown-it-katex
markdown-it-latex
katex
github-markdown-css
组件源码
<!--
* @Description: markdown显示组件
* @Author: wang keju
* @Email: git config user.email
* @Date: 2025-02-25 20:42:41
* @LastEditTime: 2025-02-27 23:28:39
* @LastEditors: wang keju
-->
<script lang="ts" setup>
import { ref, watch, onMounted } from "vue";
import MarkdownIt from 'markdown-it';
import markdownItMathjax from 'markdown-it-mathjax';
import mk from 'markdown-it-katex';
import mkl from 'markdown-it-latex';
import 'katex/dist/katex.min.css';
import "github-markdown-css";
type Props = {
text: string;
}
const props = defineProps<Props>();
const displayText = ref<string>();
const preprocessLaTeX = (content: string) => {
if (typeof content !== 'string') return content;
return content
.replace(/\\\[(.*?)\\\]/gs, (_, equation) => `$$${equation}$$`)
.replace(/\\\((.*?)\\\)/gs, (_, equation) => `$$${equation}$$`)
.replace(/(^|[^\\])\$(.+?)\$/gs, (_, prefix, equation) => `${prefix}$${equation}$`)
.replace(/\t/g, '\\t');
};
const md = new MarkdownIt({
html: true,
linkify: true,
typographer: true,
});
md.use(markdownItMathjax);
md.use(mk, {
throwOnError: false,
});
md.use(mkl);
const renderMd = (text: string) => {
text = preprocessLaTeX(text);
return md.render(text);
};
const updateDisplayText = async () => {
const info = renderMd(props.text);
displayText.value = info;
}
watch(props, updateDisplayText);
onMounted(() => {
updateDisplayText();
});
</script>
<template>
<view class="markdown-body" data-theme="light" v-html="displayText"></view>
</template>
<style lang="scss" scoped>
.markdown-body {
box-sizing: border-box;
padding: 12px;
min-height: 32px !important;
::deep(.katex-display) {
margin: 12px 0 !important;
}
}
</style>