vue渲染markdown效果

张开发
2026/4/13 20:23:58 15 分钟阅读

分享文章

vue渲染markdown效果
在 Vue 中渲染 Markdown常见做法有三种前端直接解析渲染、构建时预渲染、服务端渲染。下面按使用频率从高到低给你一套完整方案。✅ 方案一前端实时渲染最常用1️⃣ 安装依赖npm install markdown-it2️⃣ 封装一个 Markdown 组件!-- components/Markdown.vue -- template div classmarkdown-body v-htmlhtml/div /template script setup import { ref, watchEffect } from vue import MarkdownIt from markdown-it const props defineProps({ content: String }) const md new MarkdownIt({ html: true, // 允许 HTML linkify: true, // 自动识别链接 typographer: true }) const html ref() watchEffect(() { html.value md.render(props.content || ) }) /script style scoped .markdown-body { line-height: 1.75; } /style3️⃣ 使用方式Markdown :contentmdText /const mdText # 标题 - 列表项 - **加粗** \\\js console.log(Hello Vue) \\\ ✅ 优点简单灵活支持动态内容适合博客 / 文档 / 评论区⚠️ 注意v-html有 XSS 风险不要直接渲染用户输入可用markdown-it-sanitizer做过滤✅ 方案二使用现成库推荐生产环境markdown-it 插件生态npm install markdown-it markdown-it-highlightjsimport hljs from highlight.js import highlight.js/styles/github.css const md new MarkdownIt({ highlight: (str, lang) { if (lang hljs.getLanguage(lang)) { return hljs.highlight(str, { language: lang }).value } return } }) 常用插件功能插件代码高亮markdown-it-highlightjsemojimarkdown-it-emoji任务列表markdown-it-task-lists数学公式markdown-it-mathjax✅ 方案三构建时渲染性能最好适合文档站 / 博客系统示例VitePress / Nuxt Content# 文章标题 这是 Markdown 内容✅ 优点SEO 友好首屏快无需 JS 参与渲染❌ 缺点不够动态✅ 方案四SSRNuxt / SSR 项目template div v-htmlrenderedMarkdown/div /template script setup const renderedMarkdown await useMarkdown(content) /script 安全建议非常重要import sanitizeHtml from sanitize-html html.value sanitizeHtml(md.render(props.content))✅ 推荐组合最佳实践场景推荐方案后台管理 / 评论markdown-it博客 / 文档VitePress / Nuxt Content富文本编辑markdown-it sanitizer

更多文章