tiptap Code 扩展渲染成 html 的 code 标签,code 标签里的内容并不会被浏览器解析,而是可以原样输出显示,使用可以用来显示代码, pre 和 code 的区别是 pre 显示多行代码,code 一般指显示单行机器编码。
npm install @tiptap/extension-code
HTMLAttributes 自定义标签对应的HTML属性。
Code.configure({
HTMLAttributes: {
class: 'custom-class',
},
})
setCode 标记文本为code。
editor.commands.setCode()
toggleCode 切换code。
editor.commands.toggleCode()
unsetCode 移除code标记。
editor.commands.unsetCode()
Command | Windows/Linux | macOS |
---|---|---|
toggleCode() | Control E | Cmd E |
Vue 例子
React 例子
React CSS
<template>
<div v-if="editor">
<button @click="editor.chain().focus().toggleCode().run()" :class="{ 'is-active': editor.isActive('code') }">
toggleCode
</button>
<button @click="editor.chain().focus().setCode().run()" :disabled="editor.isActive('code')">
setCode
</button>
<button @click="editor.chain().focus().unsetCode().run()" :disabled="!editor.isActive('code')">
unsetCode
</button>
<editor-content :editor="editor" />
</div>
</template>
<script>
import Code from '@tiptap/extension-code'
import Document from '@tiptap/extension-document'
import Paragraph from '@tiptap/extension-paragraph'
import Text from '@tiptap/extension-text'
import { Editor, EditorContent } from '@tiptap/vue-3'
export default {
components: {
EditorContent,
},
data() {
return {
editor: null,
}
},
mounted() {
this.editor = new Editor({
extensions: [
Document,
Paragraph,
Text,
Code,
],
content: `
<p>This isn’t code.</p>
<p><code>This is code.</code></p>
`,
})
},
beforeUnmount() {
this.editor.destroy()
},
}
</script>
<style>
/* Basic editor styles */
.ProseMirror {
> * + * {
margin-top: 0.75em;
}
code {
font-size: 0.9rem;
padding: 0.25em;
border-radius: 0.25em;
background-color: rgba(#616161, 0.1);
color: #616161;
box-decoration-break: clone;
}
}
</style>
import './styles.scss'
import Code from '@tiptap/extension-code'
import Document from '@tiptap/extension-document'
import Paragraph from '@tiptap/extension-paragraph'
import Text from '@tiptap/extension-text'
import { EditorContent, useEditor } from '@tiptap/react'
import React from 'react'
export default () => {
const editor = useEditor({
extensions: [Document, Paragraph, Text, Code],
content: `
<p>This isn’t code.</p>
<p><code>This is code.</code></p>
`,
})
if (!editor) {
return null
}
return (
<>
<button
onClick={() => editor.chain().focus().toggleCode().run()}
className={editor.isActive('code') ? 'is-active' : ''}
>
toggleCode
</button>
<button
onClick={() => editor.chain().focus().setCode().run()}
disabled={editor.isActive('code')}
>
setCode
</button>
<button
onClick={() => editor.chain().focus().unsetCode().run()}
disabled={!editor.isActive('code')}
>
unsetCode
</button>
<EditorContent editor={editor} />
</>
)
}
/* Basic editor styles */
.ProseMirror {
> * + * {
margin-top: 0.75em;
}
code {
background-color: rgba(#616161, 0.1);
border-radius: 0.25em;
box-decoration-break: clone;
color: #616161;
font-size: 0.9rem;
padding: 0.25em;
}
}
本教程Demo的源码点击这里下载,Tiptap Demo,下载完成后运行npm i初始化依赖包。