DIFY api返回的数据,如何在vue保持markdown的美化样式
在Vue 中使用Dify API 返回的内容通常是 Markdown并保持美化样式核心思路是Markdown → HTML 样式highlight / 自定义 CSS下面给你几种常用且靠谱的方案从简单到专业。✅ 方案一使用marked highlight.js最常用1️⃣ 安装依赖npm install marked highlight.js2️⃣ Vue 组件中解析 Markdowntemplate div classmarkdown-body v-htmlrenderedMarkdown/div /template script setup import { ref, computed, onMounted } from vue import { marked } from marked import hljs from highlight.js import highlight.js/styles/github.css // 代码高亮主题 const markdownText ref() // Dify API 返回的 content // 配置 marked marked.setOptions({ highlight(code, lang) { if (lang hljs.getLanguage(lang)) { try { return hljs.highlight(code, { language: lang }).value } catch {} } return hljs.highlightAuto(code).value } }) const renderedMarkdown computed(() { return marked(markdownText.value) }) /script3️⃣ 添加 Markdown 基础样式很重要.markdown-body { font-size: 14px; line-height: 1.75; } .markdown-body h1, .markdown-body h2, .markdown-body h3 { margin-top: 24px; margin-bottom: 16px; } .markdown-body pre { background: #f6f8fa; padding: 16px; border-radius: 6px; overflow: auto; } .markdown-body code { font-family: monospace; }✅优点轻量可控性强适合 Dify 聊天/流式返回✅ 方案二使用markdown-it更灵活推荐企业项目安装npm install markdown-it markdown-it-highlightjs示例import MarkdownIt from markdown-it import hljs from highlight.js const md new MarkdownIt({ html: true, linkify: true, typographer: true, highlight(str, lang) { if (lang hljs.getLanguage(lang)) { return precode classhljs ${lang}${ hljs.highlight(str, { language: lang }).value }/code/pre } return } })div v-htmlmd.render(markdownText)/div✅优点插件生态好可扩展emoji、task list、数学公式✅ 方案三直接使用现成组件最快vue-markdownnpm install vue-markdownvue-markdown :sourcemarkdownText /⚠️ 缺点维护不太活跃复杂场景不推荐✅ Dify 流式响应如何处理如果 Dify 返回的是streaming markdownconst buffer ref() onMounted(async () { const reader response.body.getReader() while (true) { const { done, value } await reader.read() if (done) break buffer.value new TextDecoder().decode(value) } })然后div v-htmlrenderedMarkdown/div✅ 推荐组合实战建议场景推荐Dify 聊天机器人marked highlight.js文档/知识库markdown-it快速 demovue-markdown✅ 最终效果✅ Markdown✅ 代码高亮✅ 表格 / 列表 / 标题✅ 流式渲染不卡顿