YingXingAI/components/markdown-viewer/markdown-viewer.vue

125 lines
3.2 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<template>
<view class="markdown-container">
<mp-html :content="renderedContent" :domain="domain" :lazy-load="true" :scroll-table="true" :selectable="true" />
</view>
</template>
<script>
import { marked } from 'marked';
import hljs from 'highlight.js';
import mpHtml from '@/node_modules/mp-html/dist/uni-app/components/mp-html/mp-html.vue';
// 配置marked
marked.use({
renderer: new marked.Renderer(),
highlight: function(code, lang) {
try {
return hljs.highlightAuto(code, [lang]).value;
} catch (e) {
return hljs.highlightAuto(code).value;
}
},
gfm: true,
breaks: true,
pedantic: false,
sanitize: false,
smartLists: true,
smartypants: false
});
export default {
name: 'MarkdownViewer',
components: {
mpHtml
},
props: {
// Markdown原始内容
content: {
type: String,
default: ''
},
// 主域名(用于链接拼接)
domain: {
type: String,
default: ''
},
// 自定义样式
customStyle: {
type: String,
default: ''
}
},
computed: {
// 将Markdown转换为HTML
renderedContent() {
if (!this.content) return '';
try {
// 添加自定义样式,确保内容自动换行
const styleTag = `<style>
* {
max-width: 100% !important;
word-break: normal !important; /* 改为normal避免中文被强制断行 */
word-wrap: break-word !important;
overflow-wrap: break-word !important;
}
p {
display: inline-block !important; /* 使段落内联显示 */
white-space: normal !important;
text-align: left !important;
}
pre, code {
white-space: pre-wrap !important;
word-wrap: break-word !important;
word-break: break-all !important;
overflow-wrap: break-word !important;
}
${this.customStyle || ''}
</style>`;
// 渲染Markdown为HTML
const htmlContent = marked(this.content);
// 返回带样式的HTML
return styleTag + htmlContent;
} catch (error) {
console.error('Markdown渲染错误:', error);
return `<p style="color: red;">Markdown渲染错误: ${error.message}</p>`;
}
}
}
}
</script>
<style>
@import './highlight.css';
.markdown-container {
padding: 20rpx;
overflow-wrap: break-word;
word-wrap: break-word;
word-break: normal; /* 改为normal避免中文被强制断行 */
}
/* 全局样式,确保所有元素都能自动换行 */
.markdown-container >>> * {
max-width: 100% !important;
white-space: normal !important;
word-break: normal !important; /* 改为normal */
overflow-wrap: break-word !important;
}
/* 特别处理文本段落,避免单字换行 */
.markdown-container >>> p {
display: inline-block !important;
text-align: left !important;
}
/* 特别处理代码块 */
.markdown-container >>> pre,
.markdown-container >>> code {
white-space: pre-wrap !important;
word-break: break-all !important; /* 代码可以在任何字符间断行 */
overflow-wrap: break-word !important;
max-width: 100% !important;
}
</style>