Files
timi-web/docs/utils/markdown.md
T
2026-09-21 15:32:12 +08:00

57 lines
1.7 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Markdown 解析器
Markdown 转 HTML 的单例,内置 Prism 高亮与自定义渲染规则。
## 基础用法
:::preview 基础用法 || 左侧输入 Markdown,右侧是 toHTML 的真实输出
demo-preview=../demos/utils/markdown.vue
:::
## 何时使用
需要把 Markdown 渲染成 HTML 时使用。[MarkdownView](/components/markdown-view) 组件内部就是它,差别在于组件额外处理了容器高度与代码块折叠。
## 单例
解析器通过 `getInstance()` 获取。首次调用会注册 marked 扩展并配置 Prism 钩子,重复调用返回同一实例,不会重复注册。
```ts
const html = await Markdown.getInstance().toHTML("# 标题");
```
`toHTML` 的返回类型是 `string | Promise<string>`,两种都要 `await`;传入空值时返回空字符串。
## 扩展的语法
除了标准 Markdown(GFM、换行即换行、标题自动加 id),还改写了两个渲染规则:
**链接**:
| 写法 | 结果 |
| --- | --- |
| `[文本](https://a.com)` | 普通链接,当前窗口打开 |
| `[文本](~https://a.com)` | 链接前加 `~`,新标签页打开 |
| `[文本]()` | 没有链接时渲染为 `<span>` |
没有写 title 的链接会用文本自身作为 title。
**行内代码**:
| 写法 | 结果 |
| --- | --- |
| `` `文本` `` | `<span class="red">文本</span>` |
| `` `[red bold]文本` `` | `<span class="red bold">文本</span>` |
中括号里的是自定义类名,可以借此给行内代码上不同的样式。
## 代码块
代码块由 Prism 高亮,并带行号。行数达到 18 行时会启用折叠:双击代码块在「限制高度」与「展开全部」之间切换,最大高度取自容器上的 `data-max-height`。
## API
<utils-api name="Markdown" />