Markdown
Markdown 组件的核心基于 unified 和 remark 生态构建。它通过将 Markdown 文本解析为 AST(抽象语法树),并利用 Vue 的渲染机制将其转换为 DOM 节点。这种架构设计赋予了组件极高的灵活性,支持插槽(Slots)和自定义组件渲染,能够满足复杂的业务需求。
功能特性:
- 核心驱动:基于
unified和remark,解析精准且生态丰富。 - Vue 渲染:利用 Vue 渲染 AST,支持 Vue 组件和插槽的无缝嵌入。
- 内置支持:默认支持数学公式(KaTeX)、代码高亮、Mermaid 流程图/时序图等。
- 可扩展性:支持自定义扩展,可轻松集成 ECharts 等第三方图表库。
- 组件拆解:markdown把基本的代码高亮、Mermaid,拆解成两个组件
基础用法
基础数学公式
插槽-自定义工具栏
插槽-自定义代码块使用echarts
自定义echart文件示例 ./echarts-test.vue
vue
<template>
<div
ref="echartsDom"
style="width: 100%; height: 400px; margin: 16px 0"
></div>
</template>
<script setup lang="ts">
import { computed, onMounted, onUnmounted, useTemplateRef, watch } from 'vue'
import JSON5 from 'json5'
import * as echarts from 'echarts'
const props = defineProps({
content: {
type: String,
required: true,
},
theme: {
type: String,
default: 'light',
},
})
let myChart: echarts.ECharts | null = null
const echartsDom = useTemplateRef('echartsDom')
const options = computed(() => {
const regex = /option\s*=\s*({[\s\S]*});?$/
const match = props.content.trim().match(regex)
if (match) {
try {
return JSON5.parse(match[1])
} catch (e) {
return null
}
}
})
const renderChart = () => {
if (!echartsDom.value) return
if (!myChart) {
myChart = echarts.init(echartsDom.value, props.theme)
}
if (options.value) {
myChart.setTheme(props.theme === 'dark' ? 'dark' : 'default')
myChart.setOption(options.value)
}
}
const handleResize = () => {
myChart?.resize()
}
watch([options, () => props.theme], () => {
renderChart()
})
onMounted(() => {
renderChart()
window.addEventListener('resize', handleResize)
})
onUnmounted(() => {
if (myChart) {
myChart.dispose()
myChart = null
}
window.removeEventListener('resize', handleResize)
})
</script>
<style scoped></style>打字机输出
props
| 属性名 | 说明 | 类型 | 默认值 |
|---|---|---|---|
| theme | 主题模式 | 'dark' | 'light' | 'light' |
| content | Markdown 内容 | string | '' |
| remarkPlugins | 自定义 remark 插件 | MiddlewarePluginItem[] | [] |
| codeHighlightProps | 传递给 CodeHighlight 组件的属性 | CodeHighlightPropsType | {} |
| codeMermaidProps | 传递给 CodeMermaid 组件的属性 | CodeMermaidPropsType | {} |
slot
| 插槽名 | 说明 | 参数 |
|---|---|---|
| mermaid | 自定义 Mermaid 代码块渲染 | { content, language, theme, ...codeMermaidProps } |
| code-mermaid-toolbar | 自定义 Mermaid 工具栏 | 参见 CodeMermaid 组件文档 |
| code-mermaid-fullscreen-toolbar | 自定义 Mermaid 全屏工具栏 | 参见 CodeMermaid 组件文档 |
| code | 自定义代码块渲染 | { content, language, theme, ...codeHighlightProps } |
| code-highlight-header | 自定义代码块头部 | 参见 CodeHighlight 组件文档 |