CodeHighlighter 代码高亮
用于高亮代码格式,对齐 @ant-design/x CodeHighlighter。
何时使用
- 用于展示带语法高亮的代码片段,并提供复制功能及头部语言信息。
- 可与 Markdown / 对话气泡等内容组合,增强代码块展示与交互。
代码演示
基本
基础用法,支持多种语言与 prismLightMode 轻量模式。
JavaScript Code
javascript
import { ref } from 'vue';
import { Button } from 'ant-design-vue';
const App = () => {
const count = ref(0);
return (
<div>
<Button type="primary" onClick={() => count.value++}>
Primary Button {count.value}
</Button>
</div>
);
};
export default App;CSS Code
css
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}HTML Code
html
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>Prism Light Mode
使用 prismLightMode 属性启用轻量模式,按需加载语言支持,可显著减少打包体积。
javascript
import { ref } from 'vue';
import { Button } from 'ant-design-vue';
const App = () => {
const count = ref(0);
return (
<div>
<Button type="primary" onClick={() => count.value++}>
Primary Button {count.value}
</Button>
</div>
);
};
export default App;自定义 Header
通过 header 自定义头部内容。
Vue 计数器示例
TypeScript
import { ref } from 'vue';
function useCounter() {
const count = ref(0);
const increase = () => {
count.value += 1;
};
return { count, increase };
}API
CodeHighlighterProps
| 属性 | 说明 | 类型 | 默认值 | 版本 |
|---|---|---|---|---|
| lang | 代码语言类型 | string | - | - |
| children | 代码内容(也可通过默认插槽传入) | string | - | - |
| header | 头部内容;为 false / null 时不显示头部 | VNode | string | (() => VNode | string | false | null) | false | null | - | - |
| highlightProps | 透传到 pre 的额外属性 | object | - | - |
| prismLightMode | 是否使用 Prism 轻量模式,按 lang 按需加载语言 | boolean | true | - |
| classNames | 语义化结构 className | Record<'root' | 'header' | 'headerTitle' | 'code', string> | - | - |
| styles | 语义化结构 style | Record<'root' | 'header' | 'headerTitle' | 'code', CSSProperties> | - | - |
CodeHighlighterRef
| 属性 | 说明 | 类型 |
|---|---|---|
| nativeElement | 获取原生 DOM 节点 | HTMLDivElement | null |
CodeHighlighterSlots
| 插槽名 | 说明 |
|---|---|
| default | 代码内容 |
| header | 自定义头部 |
说明
- 底层使用
prismjs做语法高亮(React 版为react-syntax-highlighter)。 - 默认头部使用
Typography.Text的copyable提供复制(React 版为Actions.Copy)。 prismLightMode={false}会预加载一组常用语言,便于减少首次切换语言的等待。
贡献者
贡献者
正在加载贡献者信息...