vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > Vue3前端适配Markdown格式

Vue3前端适配Markdown格式问题及最佳解决方案

作者:隔壁兔爷

Markdown 编辑器作为一种轻量级文本格式,已被广泛应用于博客、文档编辑、评论系统等场景,下面这篇文章主要介绍了Vue3前端适配Markdown格式问题及最佳解决方案,文中通过代码介绍的非常详细,需要的朋友可以参考下

一、初始问题

二、解决方案对比

方案优点缺点
1. 改用 vue3-markdown-it直接支持 Vue 3,功能较完整需处理旧版依赖问题
2. 使用 markdown-it + v-html纯 JavaScript 实现,无额外依赖需手动处理 HTML 转义
3. 使用其他 Markdown 组件可能有更丰富的功能需重新学习新组件 API

三、最终推荐方案:markdown-it + v-html

1. 安装依赖

npm install markdown-it dompurify --save

2. 组件实现示例

模板部分

html

<template>
  <div class="markdown-content" v-html="parsedMarkdown"></div>
</template>

脚本部分

javascript

<script>
import { marked } from 'marked';
import DOMPurify from 'dompurify';
​
export default {
  props: {
    content: {
      type: String,
      default: ''
    },
    options: {
      type: Object,
      default: () => ({
        breaks: true,
        linkify: true,
        typographer: true
      })
    }
  },
  computed: {
    parsedMarkdown() {
      // 使用 marked 解析 Markdown
      const html = marked(this.content, this.options);
      // 使用 DOMPurify 净化 HTML
      return DOMPurify.sanitize(html);
    }
  }
}
</script>

样式部分

css

<style scoped>
.markdown-content {
  line-height: 1.6;
}
.markdown-content img {
  max-width: 100%;
}
.markdown-content pre {
  background: #f5f5f5;
  padding: 10px;
  border-radius: 4px;
  overflow-x: auto;
}
.markdown-content code {
  background: #f0f0f0;
  padding: 2px 4px;
  border-radius: 2px;
}
.markdown-content blockquote {
  border-left: 4px solid #ddd;
  padding-left: 10px;
  color: #666;
}
</style>

3. 高级功能扩展

添加 Markdown 解析器配置

javascript

import { marked } from 'marked';
import { highlight } from 'highlight.js';
import 'highlight.js/styles/github.css';
​
// 配置 marked
const md = new marked.Marked({
  highlight: function(code, lang) {
    const language = hljs.getLanguage(lang) ? lang : 'plaintext';
    return highlight(code, { language }).value;
  },
  breaks: true,
  smartLists: true,
  smartypants: true
});
​
// 在组件中使用
computed: {
  parsedMarkdown() {
    return DOMPurify.sanitize(md.parse(this.content));
  }
}

定义渲染器

const renderer = new marked.Renderer();
​
// 自定义链接渲染
renderer.link = function(href, title, text) {
  return `<a href="${href}" rel="external nofollow"  target="_blank" rel="noopener noreferrer"${title ? ` title="${title}"` : ''}>${text}</a>`;
};
​
const md = new marked.Marked({ renderer });

四、常见问题及解决

1. 表格不显示

| 表头1 | 表头2 |
|-------|-------|
| 内容1 | 内容2 |

解决:确保表格格式正确,列数一致

2. 图片不显示

![alt text](image.jpg)

解决:检查图片路径是否正确,或使用绝对路径

3. 代码高亮无效

1. 安装 highlight.js
2. 配置 marked 使用 highlight.js
3. 添加样式

五、最佳实践建议

六、性能优化

七、总结

需求解决方案
基础 Markdown 渲染使用 marked + v-html
安全防护使用 DOMPurify 净化 HTML
代码高亮集成 highlight.js
表格支持确保 Markdown 表格格式正确
图片显示检查路径或使用绝对路径
大段内容优化虚拟滚动/分块渲染
自定义样式覆盖默认样式类

通过以上方案,可以解决 Vue3 前端中 Markdown 渲染的各种常见问题,并提供良好的用户体验和安全性。

到此这篇关于Vue3前端适配Markdown格式问题及最佳解决方案的文章就介绍到这了,更多相关Vue3前端适配Markdown格式内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文