分类
Vue3使用Marked解析Markdown
Vue框架
2026-07-31
3

安装

yarn add marked

使用

import { marked } from 'marked'

let html = marked(markedText)

自定义

重写了标题、图片、链接,增加了图表,增加了代码高亮

  • 标题增加ID,可以锚点功能,使用计数器防止相同名称的ID重复
  • 图片增加了外链识别,点击后新窗口打开
  • 自定义图片宽度,语法为:![200](/logo.png)
  • 增加了MermaId图片语法支持,同时修复了HTML转义问题
  • 使用highlight实现代码高亮

具体实现代码:

yarn add mermaid
yarn add highlight.js

-----

import { marked } from 'marked'
import mermaid from 'mermaid'
import hljs from 'highlight.js'
import '../assets/atom-one-light.min.css' // 依赖包中有

// 全局标题计数器(每次渲染前重置)
let headingCounter = 0

const renderer = new marked.Renderer()

// 标题锚点
renderer.heading = function (value) {
  headingCounter++
  const id = `h-${headingCounter}`
  return `<h${value.depth} id="${id}">${value.text}</h${value.depth}>`
}

// 重写 link 方法:识别外部链接并设置 target="_blank"
renderer.link = function (data) {
  // 如果 href 以 http://, https:// 或 www. 开头,则认为是外部链接
  let isExternalLink = /^https?:\/\/|www\./i.test(data.href)
  let targetAttr = isExternalLink ? ' target="_blank"' : ''
  return `<a href="${data.href}"${targetAttr}>${data.text}</a>`
}

// 在 renderer 定义中添加以下方法
renderer.image = function (data) {
  // 原本的 text 就是 alt(即 ![alt](url) 中的 alt)
  // 现在我们尝试把 text 当作 width 使用(如 "300" 或 "300px")
  let width = ''
  if (data.text.length > 0) {
    width = 'width="'
    width += data.text.trim()
    // 如果 text 是纯数字,自动加 'px'
    if (/^\d+$/.test(width)) {
      width += 'px'
    }
    width += '"'
  }
  // 构造 img 标签,不设置 alt(或设为空),只设 width 和 src
  return `<img src="${data.href}" ${width} />`
}

// 重写 code 方法:识别 mermaid 代码块并特殊处理
renderer.code = (code) => {
  if (code.lang.trim().toLowerCase() = 'mermaid') {
    return `<div class="mermaid">${code.text}</div>`
  } else {
    const escapedCode = escapeHtml(code.text)
    return `<pre><code class="language-${code.lang
      .trim()
      .toLowerCase()}">${escapedCode}</code></pre>`
  }
}

// 辅助函数:HTML 转义
function escapeHtml(text) {
  const map = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#39;'
  }
  return text.replace(/[&<>"']/g, (m) => map[m])
}

// 注意:每次转换 markdown 前必须重置计数器!
function renderMarkdown(md) {
  headingCounter = 0 // 重置计数器
  return marked(md, { renderer })
}

// 初始化 mermaid
function initMermaid() {
  // 查找所有 .mermaid 元素
  mermaid.run({ nodes: document.getElementById('content').querySelectorAll('.mermaid') })
}
目录
统计
21
分类
39
文档
1
坚持