RichEditor 富文本编辑器
HuiRichEditor 编辑 HTML 或 Tiptap JSON,提供工具栏、链接、表格、图片上传、字数限制和全屏,并接入 HuiForm。正文排版沿用 .hui-prose;需要只读展示已保存的 HTML 时,可以使用同包的 HuiRichContent。
引入
使用 @nscode/handy-ui/editor 时先安装下列依赖。该入口同时提供富文本展示与编辑,请让应用中的 Tiptap 依赖保持同一版本。
pnpm add @floating-ui/dom@^1 dompurify@^3.4.18 @tiptap/core@3.34.0 @tiptap/pm@3.34.0 @tiptap/vue-3@3.34.0 @tiptap/starter-kit@3.34.0 @tiptap/extensions@3.34.0 @tiptap/extension-text-style@3.34.0 @tiptap/extension-text-align@3.34.0 @tiptap/extension-table@3.34.0 @tiptap/extension-image@3.34.0 @tiptap/extension-file-handler@3.34.0
应用入口加载核心主题和编辑器样式;同一应用共用一份 Vue、@nscode/handy-ui 和 Tiptap。Tiptap 相关 peer 依赖保持同一版本,不混用多份 @tiptap/core 或 @tiptap/pm。
import '@nscode/handy-ui/style.css'
import { HuiRichEditor } from '@nscode/handy-ui/editor'
import type { RichEditorExpose, RichEditorValue } from '@nscode/handy-ui/editor'
示例
HTML、创建完成与事件
默认 valueFormat="html"。update:modelValue 跟随实际编辑事务;change 在焦点离开整个编辑器后,比较本次获得焦点时的内容再触发。正文、工具栏和当前编辑器的子浮层属于同一个焦点范围,切换到颜色或链接面板不会单独提交一次 change。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSpace } from '@nscode/handy-ui'
import { HuiRichEditor } from '@nscode/handy-ui/editor'
import type { RichEditorValue } from '@nscode/handy-ui/editor'
const value = ref<RichEditorValue | null>(
'<p>选中文字,尝试<strong>加粗</strong>或插入链接。</p>'
)
const ready = ref(false)
const updates = ref(0)
const changes = ref(0)
const focuses = ref(0)
const blurs = ref(0)
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiRichEditor
v-model="value"
placeholder="请输入正文"
show-count
aria-label="基础富文本正文"
@ready="ready = true"
@update:model-value="updates++"
@change="changes++"
@focus="focuses++"
@blur="blurs++"
/>
<p role="status">
已创建:{{ ready }};更新:{{ updates }};失焦提交:{{ changes }};获得焦点:{{
focuses
}};失焦:{{ blurs }}
</p>
<pre>{{ value }}</pre>
</HuiSpace>
</template>
HTML 与 JSON
HTML 的空值为 '',JSON 的空值为 null。JSON 使用当前编辑器 schema,段落、标题等节点可能带默认属性。读取与更新事件中的 JSON 是快照,不会直接修改传入的对象。
空表格、图片、列表和带格式的空块仍有结构意义,不会因为没有纯文本就变成空值。只有默认的空段落壳等普通空内容折叠为空值。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSpace } from '@nscode/handy-ui'
import { HuiRichEditor } from '@nscode/handy-ui/editor'
import type { RichEditorValue } from '@nscode/handy-ui/editor'
const html = ref<RichEditorValue | null>('<p>这是 HTML 模型。</p>')
const json = ref<RichEditorValue | null>({
type: 'doc',
content: [
{
type: 'paragraph',
content: [{ type: 'text', text: '这是 JSON 模型。' }]
}
]
})
</script>
<template>
<HuiSpace direction="vertical" fill>
<p>valueFormat=html</p>
<HuiRichEditor v-model="html" :toolbar="['bold', 'italic']" :min-height="100" />
<pre>{{ html }}</pre>
<p>valueFormat=json</p>
<HuiRichEditor
v-model="json"
value-format="json"
:toolbar="['bold', 'italic']"
:min-height="100"
/>
<pre>{{ JSON.stringify(json, null, 2) }}</pre>
</HuiSpace>
</template>
受控拒绝与仅监听
是否传入 modelValue 决定受控状态,显式 undefined 也表示受控空值。父级拒绝候选时,正文回到父级的实际值;只监听更新而不传模型时,组件自行保存内容。不要把 update:modelValue 当成父级已接受候选的证明。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSpace } from '@nscode/handy-ui'
import { HuiRichEditor } from '@nscode/handy-ui/editor'
import type { RichEditorValue } from '@nscode/handy-ui/editor'
const rejected = ref<RichEditorValue | null>('尚未收到候选')
const listened = ref<RichEditorValue | null>('尚未编辑')
const emptyCandidate = ref<RichEditorValue | null>('尚未收到候选')
</script>
<template>
<HuiSpace direction="vertical" fill>
<p>固定父值:输入会产生候选,但父级不回填。</p>
<HuiRichEditor
model-value="<p>父级保留这段实际正文。</p>"
:toolbar="false"
:min-height="90"
@update:model-value="rejected = $event"
/>
<pre>最近被拒绝的候选:{{ rejected }}</pre>
<p>仅监听:没有 modelValue,输入会保留。</p>
<HuiRichEditor :toolbar="false" :min-height="90" @update:model-value="listened = $event" />
<pre>最近更新:{{ listened }}</pre>
<p>显式 undefined:受控空值,父级仍拒绝输入。</p>
<HuiRichEditor
:model-value="undefined"
:toolbar="false"
:min-height="90"
@update:model-value="emptyCandidate = $event"
/>
<pre>空值控件的候选:{{ emptyCandidate }}</pre>
</HuiSpace>
</template>
尺寸、禁用、只读与正文高度
size 控制工具栏控件尺寸。readonly 保留正文但隐藏工具栏,disabled 保留禁用的工具栏;两者都禁止通过组件方法或普通 Tiptap 编辑事务修改内容。外部模型回填仍然有效。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSpace, HuiSwitch } from '@nscode/handy-ui'
import { HuiRichEditor } from '@nscode/handy-ui/editor'
const disabled = ref(false)
const readonly = ref(false)
const sizes = ['small', 'default', 'large'] as const
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<label>disabled <HuiSwitch v-model="disabled" /></label>
<label>readonly <HuiSwitch v-model="readonly" /></label>
</HuiSpace>
<div v-for="size in sizes" :key="size">
<p>size={{ size }};正文 height=120、minHeight=80、maxHeight=180</p>
<HuiRichEditor
:size="size"
:disabled="disabled"
:readonly="readonly"
:toolbar="['bold', 'italic', 'link', 'fullscreen']"
:height="120"
:min-height="80"
:max-height="180"
:aria-label="`${size} 尺寸正文`"
placeholder="输入多段内容观察正文滚动"
/>
</div>
</HuiSpace>
</template>
工具栏全部内置项
工具栏数组按顺序渲染,'|' 是分隔线。下面额外列出默认工具栏没有展示的 code 和 horizontalRule。先选择文字,再选择格式;也可以用“选择全部正文”设置选区。
标题包含正文及 1~4 级标题;字号为 .75em、默认、1.5em、2.5em;对齐包含左、中、右、两端。段落和标题支持 0~8 级缩进,列表缩进沿列表自身的嵌套结构处理。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiSpace } from '@nscode/handy-ui'
import { HuiRichEditor } from '@nscode/handy-ui/editor'
import type {
RichEditorExpose,
RichEditorToolbarItem,
RichEditorValue
} from '@nscode/handy-ui/editor'
const editor = ref<RichEditorExpose>()
const value = ref<RichEditorValue | null>('<p>选择这段正文,比较标题、字号、标记与段落格式。</p>')
const toolbar: RichEditorToolbarItem[] = [
'undo',
'redo',
'|',
'heading',
'fontSize',
'|',
'bold',
'italic',
'underline',
'strike',
'code',
'color',
'backgroundColor',
'|',
'bulletList',
'orderedList',
'indent',
'outdent',
'align',
'|',
'blockquote',
'codeBlock',
'horizontalRule',
'link',
'image',
'table',
'|',
'clearFormat',
'fullscreen'
]
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiButton @click="editor?.focus('all')">选择全部正文</HuiButton>
<HuiRichEditor ref="editor" v-model="value" :toolbar="toolbar" />
<pre>{{ value }}</pre>
</HuiSpace>
</template>
颜色、段落对齐与表格
文字色和背景色分别设置;面板里的“默认”只移除对应颜色,不清除另一种颜色。颜色面板同时提供预设色和自定义颜色。序列化后的颜色可能从十六进制变为等值 rgb(...),不应按原 HTML 字节判断是否改变。
点击表格内的单元格后,表格工具展示插入行列、合并、拆分和删除操作;不在表格中时展示最大 8×8 的插入网格。删除行、列或整表会先确认范围与内容,等待期间文档变化会使旧删除失效。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSpace } from '@nscode/handy-ui'
import { HuiRichEditor } from '@nscode/handy-ui/editor'
import type { RichEditorValue } from '@nscode/handy-ui/editor'
const value = ref<RichEditorValue | null>(
[
'<p><span style="color:#1677ff;background-color:#fff2b8">选择文字后分别修改前景色和背景色。</span></p>',
'<p style="text-align:center">这段正文初始居中。</p>',
'<table><tbody>',
'<tr><th><p>事项</p></th><th><p>负责人</p></th></tr>',
'<tr><td><p>检查正文</p></td><td><p>陈晨</p></td></tr>',
'<tr><td><p>核对附件</p></td><td><p>李宁</p></td></tr>',
'</tbody></table><p>点击任意单元格后打开“表格”。</p>'
].join('')
)
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiRichEditor
v-model="value"
:toolbar="['color', 'backgroundColor', 'align', '|', 'table', 'undo', 'redo']"
/>
<pre>{{ value }}</pre>
</HuiSpace>
</template>
链接
链接面板支持地址、显示文字和新窗口选项。支持 http:、https:、mailto:、tel:、以 / 开头的地址和 # 锚点;去掉首尾空白后仍含内部空白或控制符的地址会被拒绝,不会通过拼接或删字符修成另一个地址。新窗口链接写入 noopener noreferrer。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSpace } from '@nscode/handy-ui'
import { HuiRichEditor } from '@nscode/handy-ui/editor'
import type { RichEditorValue } from '@nscode/handy-ui/editor'
const value = ref<RichEditorValue | null>(
'<p>选择文字后打开链接工具;也可点击这里的<a href="#link-preview">页内链接</a>再修改。</p>'
)
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiRichEditor v-model="value" :toolbar="['link', 'bold', 'italic']" :min-height="120" />
<p id="link-preview">编辑区内点击链接用于编辑,不直接导航。</p>
<pre>{{ value }}</pre>
</HuiSpace>
</template>
自定义工具与关闭工具栏
自定义项的 shortcut 只显示提示与 aria-keyshortcuts,不会自动注册新的快捷键。run 收到真实 Editor;组件会先核对禁用、只读、实例和焦点归属。自己直接调用原始 Editor 或编写替换插槽时,也要保留相应的交互保护。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSpace } from '@nscode/handy-ui'
import { HuiRichEditor } from '@nscode/handy-ui/editor'
import type { RichEditorToolbarItem, RichEditorValue } from '@nscode/handy-ui/editor'
const value = ref<RichEditorValue | null>('<p>选择文字后使用自定义行内代码工具。</p>')
const commands = ref(0)
const toolbar: RichEditorToolbarItem[] = [
'bold',
'|',
{
name: 'custom-code',
label: '切换行内代码',
icon: 'code-block',
shortcut: 'Mod-Shift-C',
isActive: (editor) => editor.isActive('code'),
isDisabled: (editor) => !editor.can().toggleCode(),
run: (editor) => {
editor.commands.toggleCode()
commands.value++
}
}
]
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiRichEditor v-model="value" :toolbar="toolbar" :min-height="110" />
<p role="status">自定义命令调用:{{ commands }}</p>
<p>toolbar=false:仍可编辑正文,不显示工具栏。</p>
<HuiRichEditor :toolbar="false" :min-height="90" placeholder="没有工具栏的编辑区" />
</HuiSpace>
</template>
吸顶工具栏
stickyToolbar=true 的顶部距离为 0,数字为像素偏移,false 关闭。吸顶相对实际滚动容器生效;它不会自行创建新的页面滚动区域。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiSpace } from '@nscode/handy-ui'
import { HuiRichEditor } from '@nscode/handy-ui/editor'
const sticky = ref<boolean | number>(true)
const html = Array.from(
{ length: 14 },
(_, index) => `<p>第 ${index + 1} 段:滚动此容器观察工具栏。</p>`
).join('')
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiButton @click="sticky = true">true</HuiButton>
<HuiButton @click="sticky = 24">24px</HuiButton>
<HuiButton @click="sticky = false">false</HuiButton>
</HuiSpace>
<div style="height: 280px; overflow: auto">
<HuiRichEditor
:model-value="html"
:sticky-toolbar="sticky"
:toolbar="['bold', 'italic', 'link']"
/>
</div>
<p>stickyToolbar={{ sticky }}</p>
</HuiSpace>
</template>
字数限制与统计
maxLength 接受非负有限整数,0 只允许空内容。字数按文档提取文本的 JavaScript 长度计数,部分 Unicode 字符会占两个计数单位,不是按 HTML 长度或单词数计数。超限用户事务被拦截并触发 exceed;外部回填不会被静默截短,已经超限的文档仍允许不增加计数的修正。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSpace } from '@nscode/handy-ui'
import { HuiRichEditor } from '@nscode/handy-ui/editor'
import type { RichEditorValue } from '@nscode/handy-ui/editor'
const value = ref<RichEditorValue | null>('')
const rejected = ref(0)
const lastLimit = ref<number>()
const onExceed = (limit: number) => {
rejected.value++
lastLimit.value = limit
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiRichEditor
v-model="value"
:max-length="12"
show-count
:min-height="100"
@exceed="onExceed"
/>
<p role="status">拦截次数:{{ rejected }};最近上限:{{ lastLimit ?? '未触发' }}</p>
<p>maxLength=0:尝试输入不会保留内容。</p>
<HuiRichEditor :max-length="0" :toolbar="false" :min-height="80" @exceed="onExceed" />
</HuiSpace>
</template>
表单校验
编辑器从表单继承尺寸、禁用和只读。标签与说明关联到真实正文,错误标记落在编辑器边框;工具栏里的输入框不登记成额外的业务字段。validateEvent=false 只关闭编辑器主动触发表单校验,不取消整表手动校验。
<script setup lang="ts">
import { reactive, ref } from 'vue'
import { HuiButton, HuiForm, HuiFormItem, HuiSpace, HuiSwitch } from '@nscode/handy-ui'
import type { FormRule } from '@nscode/handy-ui'
import { HuiRichEditor } from '@nscode/handy-ui/editor'
import type { RichEditorValue } from '@nscode/handy-ui/editor'
const form = ref<InstanceType<typeof HuiForm>>()
const model = reactive({ content: '' as RichEditorValue | null })
const readonly = ref(false)
const disabled = ref(false)
const validateEvent = ref(true)
const result = ref('尚未校验')
const rules: Record<string, FormRule[]> = {
content: [{ required: true, message: '请输入正文', trigger: ['change', 'blur'] }]
}
const validate = async () => {
const validation = await form.value?.validate()
result.value = validation?.valid ? '校验通过' : '正文未满足规则'
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<label>表单 readonly <HuiSwitch v-model="readonly" /></label>
<label>表单 disabled <HuiSwitch v-model="disabled" /></label>
<label>validateEvent <HuiSwitch v-model="validateEvent" /></label>
</HuiSpace>
<HuiForm
ref="form"
:model="model"
:rules="rules"
:readonly="readonly"
:disabled="disabled"
size="small"
>
<HuiFormItem label="正文" prop="content" tip="输入后移出编辑器,或点击手动校验。">
<HuiRichEditor v-model="model.content" :validate-event="validateEvent" :min-height="120" />
</HuiFormItem>
</HuiForm>
<HuiButton @click="validate">手动校验</HuiButton>
<p role="status">{{ result }}</p>
</HuiSpace>
</template>
图片上传、校验和迟到结果
图片工具支持手填地址和说明;配置 uploadImage 后,可选择、粘贴或拖入文件。适配器返回 URL 或带 src 的对象,失败时 reject。下面使用 FileReader 读取用户实际选择的图片内容,返回 Base64,因此显式开启 allowBase64Image;本例不发送到服务器,也不持久保存文件。
上传期间先显示可回收的 blob 预览,isUploading() 用于保存前检查。多文件保留插入次序,完成时替换各自的占位,失败只移除对应任务的占位。替换和移除占位不算一步编辑:撤销直接撤掉“插入图片”,撤销、重做都不会退回已回收的 blob 地址。任务通过私有状态跟踪节点位置,不把上传 ID 写进 HTML/JSON。编辑器卸载、变为只读/禁用或接受了另一份文档后,旧结果不能插回新文档;业务请求仍须由应用自行取消。
<script setup lang="ts">
import { onBeforeUnmount, ref } from 'vue'
import { HuiButton, HuiSpace, HuiSwitch } from '@nscode/handy-ui'
import { HuiRichEditor } from '@nscode/handy-ui/editor'
import type {
RichEditorExpose,
RichEditorImage,
RichEditorImageErrorReason,
RichEditorValue
} from '@nscode/handy-ui/editor'
const editor = ref<RichEditorExpose>()
const value = ref<RichEditorValue | null>('<p>使用图片工具选择文件,或直接粘贴图片。</p>')
const failUpload = ref(false)
const readonly = ref(false)
const status = ref('尚未选择图片')
const pending = new Map<FileReader, (reason: Error) => void>()
const uploadImage = (file: File): Promise<RichEditorImage> =>
new Promise((resolve, reject) => {
if (failUpload.value) {
reject(new Error('本地演示读取失败'))
return
}
const reader = new FileReader()
const finish = (error?: Error) => {
pending.delete(reader)
reader.onload = reader.onerror = reader.onabort = null
if (error) reject(error)
else if (typeof reader.result === 'string')
resolve({ src: reader.result, alt: file.name, width: 240 })
else reject(new Error('图片内容读取失败'))
}
pending.set(reader, (error) => {
reader.abort()
finish(error)
})
reader.onload = () => finish()
reader.onerror = () => finish(reader.error ?? new Error('图片内容读取失败'))
reader.onabort = () => finish(new Error('图片读取已取消'))
try {
reader.readAsDataURL(file)
} catch (error) {
finish(error instanceof Error ? error : new Error('图片内容读取失败'))
}
})
const onError = (error: Error, file: File | null, reason: RichEditorImageErrorReason) => {
status.value = `${file?.name ?? '剪贴板图片'}:${reason};${error.message}`
}
const inspect = () => {
status.value = editor.value?.isUploading()
? '仍有图片任务或尚被文档引用的本地预览'
: '没有待处理的本地图片'
}
onBeforeUnmount(() => {
for (const cancel of pending.values()) cancel(new Error('示例已卸载'))
pending.clear()
})
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<label>模拟失败 <HuiSwitch v-model="failUpload" /></label>
<label>readonly <HuiSwitch v-model="readonly" /></label>
<HuiButton @click="inspect">读取上传状态</HuiButton>
</HuiSpace>
<HuiRichEditor
ref="editor"
v-model="value"
:toolbar="['image', 'bold', 'undo', 'redo']"
:upload-image="uploadImage"
allow-base64-image
image-accept="image/png,image/jpeg,image/webp"
:image-max-size="1048576"
:readonly="readonly"
@image-error="onError"
/>
<p>仅接受 PNG/JPEG/WebP,单张最多 1 MiB;只读或卸载后,旧图片结果不再回填。</p>
<p role="status">{{ status }}</p>
<pre>{{ value }}</pre>
</HuiSpace>
</template>
imageAccept、imageMaxSize 校验实际文件,不为手填的远程 URL 发起探测请求。uploadImage 的优先级高于 Base64 回退;配置了适配器但上传失败时,不会自动改存 Base64。
Base64 回退与 Word 图片粘贴
没有上传适配器且 allowBase64Image=true 时,文件通过 FileReader 转成 Base64;默认关闭,避免模型体积过大。手填 data:image/...;base64,... 也受这个开关约束。
从支持的富文本剪贴板粘贴时,组件会匹配 HTML 中的 file: 图片与 RTF \pict 的 PNG/JPEG 数据,再进入同一套文件校验和上传流程。HTML 和剪贴板文件同时存在时,不会重复插图。无法取得的数据会移除对应本机图片、保留可解析正文,并触发 imageError(error, null, 'upload')。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSpace } from '@nscode/handy-ui'
import { HuiRichEditor } from '@nscode/handy-ui/editor'
import type { RichEditorImageErrorReason, RichEditorValue } from '@nscode/handy-ui/editor'
const value = ref<RichEditorValue | null>('')
const status = ref('可选择图片,或粘贴带 PNG/JPEG 图片的正文')
const onError = (_error: Error, file: File | null, reason: RichEditorImageErrorReason) => {
status.value = `${file?.name ?? '剪贴板图片'}:${reason}`
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiRichEditor
v-model="value"
allow-base64-image
image-accept="image/png,image/jpeg"
:image-max-size="409600"
:toolbar="['image', 'bold', 'italic', 'table']"
placeholder="在这里粘贴正文或图片"
@image-error="onError"
/>
<p role="status">{{ status }}</p>
<p>没有上传接口,本例最多接受 400 KiB 文件;输出只展示前 240 个字符。</p>
<pre>{{ String(value ?? '').slice(0, 240) }}</pre>
</HuiSpace>
</template>
RTF 图片能力不等于完整文档导入:目前不转换任意 RTF 排版、EMF/WMF 等图片或不能匹配的私有剪贴板格式。浏览器没有提供对应数据时,不能读取本机 file: 路径。它也不是 HTML 安全过滤器。
工具栏、浮动菜单与底部插槽
五个插槽均拿到当前真实 Editor。toolbar 替换整个工具栏,toolbar-prefix、toolbar-suffix 追加内容;没有 bubble-menu 时不创建选区浮动菜单。只读时隐藏工具栏和选区菜单,禁用时自定义按钮仍应显式禁止执行。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiInput, HuiSpace } from '@nscode/handy-ui'
import { HuiRichEditor } from '@nscode/handy-ui/editor'
import type { RichEditorValue } from '@nscode/handy-ui/editor'
const value = ref<RichEditorValue | null>('<p>选择文字,观察自定义选区菜单。</p>')
const note = ref('工具栏中的原生输入')
const actions = ref(0)
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiRichEditor v-model="value" :toolbar="['bold', 'italic']" show-count>
<template #toolbar-prefix>
<HuiInput
v-model="note"
:validate-event="false"
size="small"
aria-label="工具栏备注"
style="width: 180px; flex: none"
/>
</template>
<template #toolbar-suffix="{ editor }">
<HuiButton :disabled="!editor.isEditable" size="small" @click="editor.commands.focus('end')"
>正文末尾</HuiButton
>
</template>
<template #bubble-menu="{ editor }">
<HuiButton
:disabled="!editor.isEditable"
size="small"
@mousedown.prevent
@click="
() => {
editor.chain().focus().toggleBold().run()
actions++
}
"
>切换加粗</HuiButton
>
</template>
<template #footer="{ count, maxLength }">
<span
>自定义底部:{{ count }} / {{ maxLength ?? '不限' }};浮动菜单调用 {{ actions }} 次</span
>
</template>
</HuiRichEditor>
<p>完整替换 toolbar 插槽:</p>
<HuiRichEditor :min-height="100">
<template #toolbar="{ editor }">
<HuiButton
:disabled="!editor.isEditable"
@click="editor.chain().focus().toggleItalic().run()"
>自定义斜体</HuiButton
>
</template>
</HuiRichEditor>
</HuiSpace>
</template>
全屏与父弹窗
工具按钮和 toggleFullscreen() 共用同一个 bar 层:切换时不重建 Editor、正文 DOM 或选区,也不会主动把已外移的焦点抢回来。全屏使用核心共享层栈和滚动锁;先关闭当前子浮层,再由下一次 Esc 退出全屏。父弹窗关闭、禁用、只读或卸载都会退出,不会在父级重开时复活旧全屏。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiModal, HuiSpace, HuiSwitch } from '@nscode/handy-ui'
import { HuiRichEditor } from '@nscode/handy-ui/editor'
import type { RichEditorExpose, RichEditorValue } from '@nscode/handy-ui/editor'
const visible = ref(false)
const readonly = ref(false)
const editor = ref<RichEditorExpose>()
const value = ref<RichEditorValue | null>('<p>在弹窗中全屏,再打开链接或颜色面板试用 Esc。</p>')
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiButton @click="visible = true">打开编辑弹窗</HuiButton>
<HuiModal v-model:visible="visible" title="编辑正文" :width="720">
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiButton @click="editor?.toggleFullscreen(true)">进入全屏</HuiButton>
<HuiButton @click="editor?.toggleFullscreen(false)">退出全屏</HuiButton>
<label>readonly <HuiSwitch v-model="readonly" /></label>
</HuiSpace>
<HuiRichEditor
ref="editor"
v-model="value"
:readonly="readonly"
:toolbar="['bold', 'color', 'link', 'fullscreen']"
/>
</HuiSpace>
</HuiModal>
<pre>{{ value }}</pre>
</HuiSpace>
</template>
实例方法与清空确认
clear() 是底层编辑方法,不内置弹窗。所有面向用户的清空按钮应先确认对象和影响范围;确认等待期间不得提前清内容或取消图片任务。下面同时检查模型代次和真实文档快照,正文变过再变回、进入只读或卸载后,旧确认都不会清空当前文档。
<script setup lang="ts">
import { onBeforeUnmount, ref, watch } from 'vue'
import { HuiButton, HuiMessageBox, HuiSpace, HuiSwitch } from '@nscode/handy-ui'
import { HuiRichEditor } from '@nscode/handy-ui/editor'
import type { RichEditorExpose, RichEditorValue } from '@nscode/handy-ui/editor'
const editor = ref<RichEditorExpose>()
const value = ref<RichEditorValue | null>('<p>这是可查询、追加和确认清空的正文。</p>')
const readonly = ref(false)
const pending = ref(false)
const status = ref('尚未调用实例方法')
let alive = true
let revision = 0
watch(
[value, readonly],
() => {
revision++
},
{ deep: true, flush: 'sync' }
)
onBeforeUnmount(() => {
alive = false
revision++
})
const inspect = () => {
const api = editor.value
if (!api) return
status.value = JSON.stringify(
{
html: api.getHTML(),
json: api.getJSON(),
text: api.getText(),
uploading: api.isUploading(),
ready: !!api.editor
},
null,
2
)
}
const clear = async () => {
const api = editor.value
const instance = api?.editor
if (
!api ||
!instance ||
instance.isDestroyed ||
readonly.value ||
pending.value ||
value.value === '' ||
value.value === null
)
return
const request = revision
const snapshot = instance.state.doc
pending.value = true
try {
const result = await HuiMessageBox.confirm({
title: '清空当前正文',
message: '确定清空当前正文吗?文字、表格和图片会一并移除;尚未完成的本地图片任务将失效。',
type: 'warning',
confirmButtonText: '清空正文',
confirmButtonType: 'danger'
})
if (!alive) return
if (
readonly.value ||
revision !== request ||
editor.value?.editor !== instance ||
instance.isDestroyed ||
instance.state.doc !== snapshot
) {
status.value = '正文或编辑状态已变化,请重新确认'
return
}
if (result.action !== 'confirm') {
status.value = '已取消或关闭,正文保留'
return
}
api.clear()
status.value = '已请求清空;实际结果仍遵循父级模型'
} catch {
if (alive) status.value = '已取消或关闭,正文保留'
} finally {
if (alive) pending.value = false
}
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiButton @click="editor?.focus('start')">聚焦开头</HuiButton>
<HuiButton @click="editor?.focus('end')">聚焦结尾</HuiButton>
<HuiButton @click="editor?.focus('all')">选择全部</HuiButton>
<HuiButton @click="editor?.focus(1)">聚焦位置 1</HuiButton>
<HuiButton @mousedown.prevent @click="editor?.blur()">移出当前焦点</HuiButton>
<HuiButton :disabled="readonly" @click="editor?.insertContent('<strong>追加 HTML</strong>')"
>插入 HTML</HuiButton
>
<HuiButton
:disabled="readonly"
@click="editor?.insertContent({ type: 'text', text: '追加 JSON 文本' })"
>插入 JSON</HuiButton
>
<HuiButton @click="inspect">查询 HTML / JSON / 文本 / 上传状态</HuiButton>
<HuiButton
type="danger"
:loading="pending"
:disabled="readonly || value === '' || value === null"
@click="clear"
>确认清空</HuiButton
>
<label>readonly <HuiSwitch v-model="readonly" /></label>
</HuiSpace>
<HuiRichEditor
ref="editor"
v-model="value"
:readonly="readonly"
:toolbar="['bold', 'image', 'table', 'fullscreen']"
/>
<pre role="status">{{ status }}</pre>
</HuiSpace>
</template>
旧格式与创建配置
legacyFormat="quill" 仅在读入 HTML 时先调用同包 convertQuillHtml,再交给当前 schema;更新输出为当前编辑器格式。starterKit、extensions 只在创建时读取,不支持运行中替换扩展而保留原实例。下面关闭标题和两种列表扩展,同时不展示对应工具。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSpace } from '@nscode/handy-ui'
import { HuiRichEditor } from '@nscode/handy-ui/editor'
import type { RichEditorValue } from '@nscode/handy-ui/editor'
const value = ref<RichEditorValue | null>(
'<p class="ql-align-center"><span class="ql-size-large">读入旧正文,输出使用当前格式。</span></p>'
)
const starterKit = { heading: false, bulletList: false, orderedList: false } as const
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiRichEditor
v-model="value"
legacy-format="quill"
:starter-kit="starterKit"
:toolbar="['bold', 'italic', 'fontSize', 'align', 'link']"
/>
<pre>{{ value }}</pre>
</HuiSpace>
</template>
简体、繁体与英文界面
组件复用现有 HuiConfigProvider 语言链,内置简体、繁体、英文资源。此处切换的是界面文案,不翻译已输入正文。自定义工具和插槽的文字仍由应用提供。
<script setup lang="ts">
import { computed, ref } from 'vue'
import {
HuiButton,
HuiConfigProvider,
HuiSpace,
localeEn,
localeZhCn,
localeZhTw
} from '@nscode/handy-ui'
import { HuiRichEditor } from '@nscode/handy-ui/editor'
const language = ref<'zh-cn' | 'zh-tw' | 'en'>('zh-cn')
const locale = computed(
() => ({ 'zh-cn': localeZhCn, 'zh-tw': localeZhTw, en: localeEn })[language.value]
)
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiButton @click="language = 'zh-cn'">简体中文</HuiButton>
<HuiButton @click="language = 'zh-tw'">繁體中文</HuiButton>
<HuiButton @click="language = 'en'">English</HuiButton>
</HuiSpace>
<HuiConfigProvider :locale="locale">
<HuiRichEditor
show-count
:max-length="80"
:toolbar="['heading', 'color', 'link', 'image', 'table', 'fullscreen']"
/>
</HuiConfigProvider>
</HuiSpace>
</template>
其他语言
主入口只带简体、繁体、英文三种富文本语言包。其余 76 种从 @nscode/handy-ui/editor/locale/<语言> 导入,默认导出就是语言包,和核心语言包合在一起传给 app.use 或 HuiConfigProvider 的 locale。只传了核心语言包时,编辑器的文字退回简体中文。
import { createApp } from 'vue'
import HandyUI from '@nscode/handy-ui'
import jaJp from '@nscode/handy-ui/locale/ja-jp'
import editorJaJp from '@nscode/handy-ui/editor/locale/ja-jp'
import App from './App.vue'
// 核心语言包和富文本语言包合在一起传
createApp(App)
.use(HandyUI, { locale: { ...jaJp, ...editorJaJp } })
.mount('#app')
Props
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| modelValue / v-model | RichEditorValue | null | undefined | 按格式为空 | 按属性存在性受控;只监听更新不构成受控,显式 undefined 是受控空值 |
| valueFormat | 'html' | 'json' | 'html' | 输出格式,空值分别为 ''、null |
| placeholder | string | — | 占位文字;空字符串是显式覆盖 |
| disabled | boolean | false | 禁止编辑,保留禁用的工具栏;继承表单禁用 |
| readonly | boolean | false | 禁止编辑并隐藏工具栏、选区菜单;继承表单只读 |
| toolbar | RichEditorToolbarItem[] | false | 默认工具栏 | 顺序、分隔线、自定义工具;false 隐藏 |
| stickyToolbar | boolean | number | 关闭 | true 顶部偏移为 0,数字表示 px |
| height | number | string | — | 正文区高度;数值按 px |
| minHeight | number | string | 240 | 正文区最小高度;全屏时由剩余空间分配 |
| maxHeight | number | string | — | 正文区最大高度,超出滚动 |
| maxLength | number | 不限 | 非负有限整数;0 只允许空内容;外部回填不裁剪 |
| showCount | boolean | false | 显示字数;提供有效 maxLength 时也显示计数 |
| uploadImage | RichEditorUploadImage | — | 文件上传适配器;返回 URL 或图片对象,reject 表示失败 |
| imageAccept | string | 'image/*' | 文件类型规则,支持 MIME、通配 MIME、扩展名 |
| imageMaxSize | number | 不限 | 单文件最大字节数,正数时生效 |
| allowBase64Image | boolean | false | 无上传适配器时允许 Base64 回退,并允许相应图片地址 |
| extensions | Extensions | [] | 追加 Tiptap 扩展,只在创建时读取 |
| starterKit | Partial<StarterKitOptions> | 内置配置 | 创建时配置;不要与内置节点、mark 重复注册同名扩展 |
| legacyFormat | 'quill' | — | HTML 先做旧格式转换,不是 HTML 过滤开关 |
| size | ComponentSize | 继承 | small、default、large;沿现有表单和全局尺寸链 |
| validateEvent | boolean | true | 是否主动触发表单变化、失焦校验 |
class、style 落在编辑器外框;id、ARIA、其他原生属性和监听落在实际正文。自定义 aria-label、aria-labelledby(包括空字符串)优先于表单自动命名,aria-describedby 与表单说明、错误 ID 合并。
Events
| 事件 | 参数 | 说明 |
|---|---|---|
| update:modelValue | (value: RichEditorValue | null) | 提交编辑候选;不证明父级已接受 |
| change | (value: RichEditorValue | null) | 离开整个编辑器,实际内容相较获得焦点时有变化;blur 先于此事件 |
| focus | (event: FocusEvent) | 焦点首次进入正文、工具栏或本实例子浮层范围 |
| blur | (event: FocusEvent) | 焦点离开整个范围;内部面板切换不重复触发 |
| ready | (editor: Editor) | 客户端创建完成;SSR 不触发 |
| imageError | (error: Error, file: File | null, reason: RichEditorImageErrorReason) | 类型、大小、上传或缺少适配器;无法恢复的剪贴板本机图片 file=null |
| exceed | (maxLength: number) | 用户事务被有效字数上限拦截 |
模板可用 @image-error 等短横线监听写法,组件声明的事件名保持驼峰。没有额外的 clear 事件;清空遵循更新候选与失焦 change 合同。
Slots
| 插槽 | 参数 | 说明 |
|---|---|---|
| toolbar | { editor } | 替换整个工具栏,toolbar=false 或只读时不渲染 |
| toolbar-prefix | { editor } | 默认工具栏前部 |
| toolbar-suffix | { editor } | 默认工具栏尾部 |
| bubble-menu | { editor } | 选区浮动菜单;未提供则不创建 |
| footer | { editor, count, maxLength } | 替换计数区域;无有效上限时 maxLength 为 undefined |
方法
通过模板 ref 获取 RichEditorExpose。实例创建前 editor 为 undefined;其他方法按当前实例生命周期与禁用、只读边界执行。
| 成员 | 类型 | 说明 |
|---|---|---|
| editor | readonly Editor | undefined | 真实 Tiptap 实例;进阶命令需要应用自行遵守交互、确认规则 |
| focus | (position?: 'start' | 'end' | 'all' | number) => void | 聚焦正文并可调整选区;禁用时不聚焦 |
| blur | () => void | 只移出当前属于本实例的焦点 |
| clear | () => void | 请求清空;受控父拒绝时恢复实际值;用户入口须先确认 |
| getHTML | () => string | 查询当前实际 HTML;普通空文档可能仍序列化为 <p></p> |
| getJSON | () => JSONContent | 查询当前实际 JSON 快照 |
| getText | () => string | 查询当前实际纯文本;没有文本不等于没有结构内容 |
| insertContent | (content: string | JSONContent) => void | 在选区插入内容;遵守禁写与字数限制 |
| toggleFullscreen | (value?: boolean) => void | 指定进入/退出,不传反转;禁用、只读、父层关闭时不能进入 |
| isUploading | () => boolean | 是否还有图片任务或文档仍引用尚未完成保存的本地 blob |
类型
从 @nscode/handy-ui/editor 引入公开的 RichEditorProps、RichEditorEmits、RichEditorExpose、RichEditorSlots、RichEditorValueFormat、RichEditorValue、RichEditorToolName、RichEditorToolbarItem、RichEditorCustomTool、RichEditorImage、RichEditorUploadImage、RichEditorImageErrorReason。
type RichEditorValueFormat = 'html' | 'json'
type RichEditorValue = string | JSONContent
type RichEditorImageErrorReason = 'type' | 'size' | 'upload' | 'missing'
interface RichEditorImage {
src: string
alt?: string
title?: string
width?: number
height?: number
}
type RichEditorUploadImage = (file: File) => Promise<string | RichEditorImage>
JSONContent、Editor、Extensions 属于 Tiptap;ComponentSize 来自 @nscode/utils。内置工具共 24 项,另有分隔线 '|'。默认不展示 code 和 horizontalRule,可以按需加入。
键盘操作
- 正文
Alt+F10进入工具栏。工具栏左右方向键移动,Home、End 到首尾,禁用项跳过;工具栏自身只有一个 Tab 入口。插槽内输入框保留原生文字编辑按键。 - 非全屏工具栏按 Esc 回正文。全屏时先由当前子浮层处理 Esc,之后退出本实例全屏,不关闭兄弟编辑器;关闭子层后的焦点回到相应触发器。
- 正文支持 Tiptap 的加粗、斜体等命令快捷键;
Ctrl+K/Meta+K打开链接工具。自定义项的shortcut只负责提示,不增加全局键盘监听。 - 段落或标题中的 Tab、Shift+Tab 执行缩进、减少缩进;列表、代码块沿自身扩展规则处理。IME 组合输入不触发工具栏导航。