RichContent 富文本展示
展示 HTML 或默认插槽中的正文,沿用 HandyUI 的主题、语言、排版和图片预览。它不编辑内容,不接入表单模型,也不提供公开实例方法。
引入
使用 @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。应用入口加载核心主题和本包样式,页面按需导入真实组件:
import '@nscode/handy-ui/style.css'
import { HuiRichContent } from '@nscode/handy-ui/editor'
核心样式已包含主题;本组件使用 .hui-prose 排版类。样式路径用于包产物接入,使用源码时由宿主配置对应别名。
示例
基础正文
通过 html 传入正文。标题、段落、列表、引用、代码和表格沿用现有排版主题;HTML 字符串中的组件名或 Vue 指令不会作为 Vue 组件编译。
<script setup lang="ts">
import { HuiRichContent } from '@nscode/handy-ui/editor'
const html = [
'<h2>发布说明</h2>',
'<p>正文可包含<strong>重点</strong>、<em>说明</em>和<code>version</code>。</p>',
'<ul><li>检查内容</li><li>确认结果</li></ul>',
'<blockquote>发布前保留完整的内容快照。</blockquote>',
'<pre><code>const total = 3</code></pre>',
'<table><thead><tr><th>项目</th><th>状态</th></tr></thead>',
'<tbody><tr><td>文档</td><td>已更新</td></tr></tbody></table>'
].join('')
</script>
<template>
<HuiRichContent :html="html" aria-label="发布说明正文" />
</template>
默认插槽与空 HTML
未提供 html 时显示真实默认插槽,插槽中的 Vue 事件照常工作;提供 html="" 会显示空 HTML,不回退到插槽。将 html 改回 undefined 后才恢复插槽。默认插槽不经过 HTML 过滤器,内容由应用自己的 Vue 模板负责。
<script setup lang="ts">
import { computed, ref } from 'vue'
import { HuiButton, HuiSpace } from '@nscode/handy-ui'
import { HuiRichContent } from '@nscode/handy-ui/editor'
const mode = ref<'slot' | 'empty' | 'html'>('slot')
const clicks = ref(0)
const html = computed(() =>
mode.value === 'slot' ? undefined : mode.value === 'empty' ? '' : '<p>当前使用 HTML 正文。</p>'
)
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiButton @click="mode = 'slot'">使用默认插槽</HuiButton>
<HuiButton @click="mode = 'empty'">显式空 HTML</HuiButton>
<HuiButton @click="mode = 'html'">使用 HTML</HuiButton>
</HuiSpace>
<p>模式:{{ mode }};插槽按钮点击:{{ clicks }}</p>
<HuiRichContent :html="html" tag="section" aria-label="正文与插槽优先级">
<p>这是默认插槽。</p>
<HuiButton @click="clicks++">插槽按钮</HuiButton>
</HuiRichContent>
</HuiSpace>
</template>
三种字号
small、default、large 控制正文的字号档位,不作为表单控件尺寸。本组件默认 default;未承诺从 Form 或 ConfigProvider 自动继承字号。
<script setup lang="ts">
import { HuiSpace } from '@nscode/handy-ui'
import { HuiRichContent } from '@nscode/handy-ui/editor'
const sizes = ['small', 'default', 'large'] as const
const html = '<p>这是一段正文,包含<strong>重点文字</strong>和<code>inline code</code>。</p>'
</script>
<template>
<HuiSpace direction="vertical" fill>
<div v-for="size in sizes" :key="size">
<p>size={{ size }}</p>
<HuiRichContent :size="size" :html="html" />
</div>
</HuiSpace>
</template>
根标签、样式与原生属性
tag 决定实际排版根标签。class、style、id、ARIA 和原生监听都落在这个根节点,可以动态替换或移除;不会额外包一层展示容器。请按内容选择合适的原生标签,本例使用 article、section 和 div。
<script setup lang="ts">
import { computed, ref } from 'vue'
import { HuiButton, HuiSpace } from '@nscode/handy-ui'
import { HuiRichContent } from '@nscode/handy-ui/editor'
const tag = ref('article')
const named = ref(true)
const clicks = ref(0)
const target = ref('尚未点击')
const attributes = computed(() =>
named.value ? { 'aria-label': '项目说明', title: '点击正文查看根节点' } : {}
)
const onClick = (event: MouseEvent) => {
clicks.value++
target.value = (event.currentTarget as HTMLElement).tagName.toLowerCase()
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiButton v-for="value in ['article', 'section', 'div']" :key="value" @click="tag = value">
tag={{ value }}
</HuiButton>
<HuiButton @click="named = !named">{{ named ? '移除名称属性' : '恢复名称属性' }}</HuiButton>
</HuiSpace>
<HuiRichContent
v-bind="attributes"
:tag="tag"
class="rich-content-root-example"
style="padding: var(--hui-spacing-4); border: var(--hui-border-width) solid var(--hui-border-color)"
html="<p>点击<strong>这段正文</strong>,原生事件仍从实际子节点冒泡。</p>"
@click="onClick"
/>
<p role="status">原生点击:{{ clicks }};currentTarget:{{ target }}</p>
</HuiSpace>
</template>
默认安全过滤
sanitize 默认 true,使用 DOMPurify 过滤。下面的 onclick="return false" 和危险协议仅用于观察过滤,示例不会执行警报或发起请求。默认规则移除事件属性、危险链接以及脚本、样式节点和表单控件,style 属性只留排版类声明;普通排版内容保留。点击“读取过滤结果”查看实际 DOM。
<script setup lang="ts">
import { nextTick, onMounted, ref } from 'vue'
import { HuiButton, HuiSpace } from '@nscode/handy-ui'
import { HuiRichContent } from '@nscode/handy-ui/editor'
const host = ref<HTMLElement>()
const status = ref('等待客户端挂载')
const html = [
'<p data-sample="content" onclick="return false">事件属性会被移除,<strong>加粗正文</strong>保留。</p>',
'<p><a href="javascript:void(0)">危险协议链接只保留文字</a></p>',
'<input value="不会留下的表单控件">'
].join('')
const inspect = async () => {
await nextTick()
const body = host.value?.querySelector('.hui-rich-content')
status.value = body
? 'onclick 保留:' +
body.hasAttribute('onclick') +
';后代事件属性:' +
!!body.querySelector('[onclick]') +
';链接 href:' +
(body.querySelector('a')?.getAttribute('href') ?? '已移除') +
';input 保留:' +
!!body.querySelector('input')
: '正文尚未挂载'
}
onMounted(inspect)
</script>
<template>
<HuiSpace direction="vertical" fill>
<div ref="host"><HuiRichContent :html="html" aria-label="默认过滤示例" /></div>
<HuiButton @click="inspect">读取过滤结果</HuiButton>
<p role="status">{{ status }}</p>
<pre>{{ html }}</pre>
</HuiSpace>
</template>
可信 HTML 关闭过滤
sanitize=false 原样使用可信 HTML。下面只使用本地静态内容,不包含可执行事件;对比可见原生按钮是否保留。关闭过滤不等于内容已安全,不应与上例的不可信输入共用开关。
<script setup lang="ts">
import { HuiSpace } from '@nscode/handy-ui'
import { HuiRichContent } from '@nscode/handy-ui/editor'
const html =
'<p>本地静态正文。</p><button type="button" data-trusted="yes">本地 HTML 按钮</button>'
</script>
<template>
<HuiSpace direction="vertical" fill>
<div>
<p>默认过滤:移除原生按钮</p>
<HuiRichContent :html="html" />
</div>
<div>
<p>sanitize=false:保留本地静态按钮</p>
<HuiRichContent :html="html" :sanitize="false" />
</div>
</HuiSpace>
</template>
增补过滤选项
allowTags、allowAttrs 是默认规则的增补,不是重新定义完整白名单;forbidTags 追加禁止标签,禁止优先。只在默认过滤时使用这些选项。下面保留自定义标签和属性,并切换是否保留 strong;正文文字不因此丢失。
<script setup lang="ts">
import { computed, nextTick, onMounted, ref } from 'vue'
import { HuiButton, HuiCheckbox, HuiSpace } from '@nscode/handy-ui'
import { HuiRichContent } from '@nscode/handy-ui/editor'
import type { RichContentSanitizeOptions } from '@nscode/handy-ui/editor'
const blockStrong = ref(true)
const host = ref<HTMLElement>()
const status = ref('等待读取')
const html =
'<custom-note note-id="42"><strong>重要正文</strong>,<em>补充说明</em>。</custom-note>'
const options = computed<RichContentSanitizeOptions>(() => ({
allowTags: ['custom-note'],
allowAttrs: ['note-id'],
forbidTags: blockStrong.value ? ['strong'] : []
}))
const inspect = async () => {
await nextTick()
const note = host.value?.querySelector('custom-note')
status.value =
'custom-note:' +
!!note +
';note-id:' +
(note?.getAttribute('note-id') ?? '无') +
';strong:' +
!!note?.querySelector('strong')
}
onMounted(inspect)
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiCheckbox v-model="blockStrong">禁止 strong 标签</HuiCheckbox>
<div ref="host"><HuiRichContent :html="html" :sanitize-options="options" /></div>
<HuiButton @click="inspect">读取当前结构</HuiButton>
<p role="status">{{ status }}</p>
</HuiSpace>
</template>
样式过滤
默认过滤只保留 style 里的排版类声明:颜色、背景色、字号、字体、字重、字形、行高、字间距、对齐、文字装饰、首行缩进、垂直对齐、换行、列表符号、宽高、边框和内边距,编辑器写出的样式都在其中。position、z-index、transform、margin、display、opacity 这类能把内容挪出正文、盖住页面的声明会被去掉,防止内容用一层透明元素盖住整页诱导点击;含 url() 的值一律去掉。全部去掉时,整个 style 属性一起移除。确实需要的属性用 allowStyles 追加,按前缀匹配,例如 ['margin'] 同时放行 margin-top 等分项。下面切换是否追加 margin,读取过滤后的样式。
<script setup lang="ts">
import { computed, nextTick, onMounted, ref, watch } from 'vue'
import { HuiButton, HuiCheckbox, HuiSpace } from '@nscode/handy-ui'
import { HuiRichContent } from '@nscode/handy-ui/editor'
import type { RichContentSanitizeOptions } from '@nscode/handy-ui/editor'
const allowMargin = ref(false)
const host = ref<HTMLElement>()
const status = ref('等待读取')
const html = [
'<p data-sample="mixed" style="color: #c0392b; text-align: center; margin: 16px 0; position: relative; top: 8px; z-index: 10">颜色、对齐保留;外边距看是否追加;定位、层级去掉。</p>',
'<p data-sample="layout" style="position: relative; left: 24px; z-index: 10">只写了定位和层级,整个 style 属性被移除。</p>'
].join('')
const options = computed<RichContentSanitizeOptions>(() => ({
allowStyles: allowMargin.value ? ['margin'] : []
}))
const inspect = async () => {
await nextTick()
const read = (name: string) =>
host.value?.querySelector(`[data-sample="${name}"]`)?.getAttribute('style') ??
'(没有 style)'
status.value = '第一段:' + read('mixed') + ';第二段:' + read('layout')
}
watch(allowMargin, inspect)
onMounted(inspect)
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiCheckbox v-model="allowMargin">追加 margin</HuiCheckbox>
<div ref="host"><HuiRichContent :html="html" :sanitize-options="options" /></div>
<HuiButton @click="inspect">读取过滤后的样式</HuiButton>
<p role="status">{{ status }}</p>
</HuiSpace>
</template>
同步替代过滤与失败为空
函数形式的 sanitize 收到待过滤 HTML,完全替代默认过滤,sanitizeOptions 不再参与;未设置 legacyFormat 时是原始输入,设置后是已转换的 HTML。必须同步返回字符串;抛错或返回非字符串时显示空正文,开发环境给出诊断。下面只从输入长度构造固定摘要,不把原文插回输出,不把这个摘要函数当作通用安全过滤器。
<script setup lang="ts">
import { computed, ref } from 'vue'
import { HuiButton, HuiCheckbox, HuiSpace } from '@nscode/handy-ui'
import { HuiRichContent } from '@nscode/handy-ui/editor'
const html = ref('<h2>原始正文</h2><p>用于构造摘要。</p>')
const fail = ref(false)
const filter = computed(() => (original: string): string => {
if (fail.value) throw new Error('演示同步过滤失败')
return '<p data-summary="yes">已收到原始 HTML,共 ' + original.length + ' 个字符。</p>'
})
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiCheckbox v-model="fail">演示过滤器抛错,正文保持为空</HuiCheckbox>
<HuiButton @click="html += '<p>新增段落。</p>'">更新原始 HTML</HuiButton>
<p>输入长度:{{ html.length }};失败模式:{{ fail }}</p>
<HuiRichContent :html="html" :sanitize="filter" aria-label="同步摘要结果" />
</HuiSpace>
</template>
链接事件、取消跳转与原生事件
linkClick(event, href) 中的 href 是当前链接属性。调用 event.preventDefault() 取消同一次浏览器默认跳转;默认过滤已经移除 href 的链接不会发虚假通知。原生 click 仍由实际子节点冒泡到排版根,不替代组件事件。下面只跳本页锚点,不请求外部地址。
<script setup lang="ts">
import { ref, useId } from 'vue'
import { HuiCheckbox, HuiSpace } from '@nscode/handy-ui'
import { HuiRichContent } from '@nscode/handy-ui/editor'
const destination = useId()
const cancel = ref(true)
const status = ref('尚未点击链接')
const nativeClicks = ref(0)
const html = '<p><a href="#' + destination + '"><strong>本页目标</strong></a></p>'
const onLinkClick = (event: MouseEvent, href: string) => {
if (cancel.value) event.preventDefault()
status.value = 'href=' + href + ';已取消=' + event.defaultPrevented
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiCheckbox v-model="cancel">取消默认锚点跳转</HuiCheckbox>
<HuiRichContent :html="html" @link-click="onLinkClick" @click="nativeClicks++" />
<p role="status">{{ status }};原生 click:{{ nativeClicks }}</p>
<p :id="destination" tabindex="-1">这是当前示例的目标段落。</p>
</HuiSpace>
</template>
图片预览、取消与动态正文
图片全部为本地 SVG。imageClick(event, src, index) 的下标按当前容器图片节点计算,重复 URL 也各有位置;preventDefault() 可取消预览。关闭 previewImage 后仍通知点击,但不自动增加预览键盘入口。先点“三秒后更换正文”,再打开任意图片,可观察更换内容后旧预览失效。计时器在卸载时清理。
<script setup lang="ts">
import { computed, onBeforeUnmount, ref } from 'vue'
import { HuiButton, HuiCheckbox, HuiSpace } from '@nscode/handy-ui'
import { HuiRichContent } from '@nscode/handy-ui/editor'
const picture = (title: string, color: string) =>
'data:image/svg+xml;charset=utf-8,' +
encodeURIComponent(
'<svg xmlns="http://www.w3.org/2000/svg" width="240" height="120">' +
'<rect width="240" height="120" fill="' +
color +
'"/>' +
'<text x="120" y="68" text-anchor="middle" fill="white" font-size="24">' +
title +
'</text></svg>'
)
const first = picture('示意图一', '#409eff')
const second = picture('示意图二', '#67c23a')
const version = ref(1)
const preview = ref(true)
const cancel = ref(false)
const status = ref('点击图片,或用 Tab 聚焦后按 Enter / 空格。')
const updateStatus = ref('尚未安排更新')
const html = computed(
() =>
'<p>正文版本 ' +
version.value +
'</p>' +
'<img src="' +
first +
'" alt="流程示意图一">' +
'<img src="' +
second +
'" alt="流程示意图二">' +
'<img src="' +
first +
'" alt="流程示意图一的重复位置">'
)
let alive = true
let timer: ReturnType<typeof setTimeout> | undefined
const onImageClick = (event: MouseEvent, src: string, index: number) => {
if (cancel.value) event.preventDefault()
status.value =
'index=' +
index +
';本地 SVG=' +
src.startsWith('data:image/svg+xml') +
';取消=' +
event.defaultPrevented
}
const schedule = () => {
if (timer !== undefined) clearTimeout(timer)
updateStatus.value = '三秒后更新;现在可以打开预览。'
timer = setTimeout(() => {
timer = undefined
if (!alive) return
version.value++
updateStatus.value = '正文已更新,旧预览已失效。'
}, 3000)
}
onBeforeUnmount(() => {
alive = false
if (timer !== undefined) clearTimeout(timer)
})
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiCheckbox v-model="preview">启用默认图片预览</HuiCheckbox>
<HuiCheckbox v-model="cancel">取消本次图片预览</HuiCheckbox>
<HuiButton @click="schedule">三秒后更换正文</HuiButton>
</HuiSpace>
<p role="status">{{ status }};{{ updateStatus }}</p>
<HuiRichContent :html="html" :preview-image="preview" @image-click="onImageClick" />
</HuiSpace>
</template>
旧格式正文与独立转换
legacyFormat="quill" 在客户端挂载后先转换旧格式,再交给默认或自定义过滤。sanitize=false 只跳过过滤,不跳过转换。下面用本地构造的对齐、缩进、列表和代码块展示;点击按钮可查看公开工具 convertQuillHtml() 的转换结果,结果只作文字显示。工具仅转换格式,不清理脚本、事件属性或 URL;缺少 DOMParser 时直接调用会抛出中文环境错误。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiSpace } from '@nscode/handy-ui'
import { convertQuillHtml, HuiRichContent } from '@nscode/handy-ui/editor'
const html = [
'<p class="ql-align-center ql-size-large">旧格式标题</p>',
'<p class="ql-indent-2">缩进正文。</p>',
'<ol><li data-list="bullet">事项一</li>',
'<li data-list="bullet" class="ql-indent-1">下一级事项</li>',
'<li data-list="ordered">步骤一</li></ol>',
'<div class="ql-code-block-container"><div class="ql-code-block">const total = 1</div>',
'<div class="ql-code-block">total + 1</div></div>'
].join('')
const converted = ref('点击按钮后读取,服务端不调用 DOMParser。')
const convert = () => {
converted.value = convertQuillHtml(html)
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiRichContent :html="html" legacy-format="quill" aria-label="旧格式正文" />
<HuiButton @click="convert">查看格式转换结果</HuiButton>
<pre>{{ converted }}</pre>
</HuiSpace>
</template>
Props
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| html | string | undefined | HTML 正文;未提供时显示默认插槽,空字符串优先于插槽 |
| sanitize | boolean | ((html: string) => string) | true | 默认 DOMPurify;false 用于可信 HTML;同步函数完全替代默认过滤 |
| sanitizeOptions | RichContentSanitizeOptions | — | 默认过滤的标签/属性增补和禁止标签 |
| previewImage | boolean | true | 是否启用默认图片预览;false 仍保留 imageClick 通知 |
| size | 'small' | 'default' | 'large' | 'default' | 正文字号档位 |
| tag | string | 'div' | 实际排版根标签 |
| legacyFormat | 'quill' | undefined | 挂载后先转换旧格式,再按 sanitize 处理 |
RichContentSanitizeOptions
| 字段 | 类型 | 说明 |
|---|---|---|
| allowTags | string[] | 在默认规则上增补标签 |
| allowAttrs | string[] | 在默认规则上增补属性 |
| forbidTags | string[] | 追加禁止标签,优先于允许配置 |
| allowStyles | string[] | 在默认样式白名单上追加属性,按前缀匹配分项属性 |
它不是完整的 DOMPurify 配置对象,也不接收持久实例。默认过滤额外保留 target、data-indent,禁止 style/form/input/button/textarea/select 标签;style 属性只保留排版类声明,含 url() 的值去掉(见“样式过滤”);带 target 的链接(a、area)只要不是 _self、_parent、_top,就移除 opener 并补齐 noopener、noreferrer;target="report" 这类命名窗口也一样,防止打开的页面通过 window.opener 改写原页面地址。关闭过滤或用自定义函数替代时,这些默认处理不再生效。
Events
| 事件 | 参数 | 说明 |
|---|---|---|
| linkClick | (event: MouseEvent, href: string) | 当前链接点击;preventDefault 取消默认跳转 |
| imageClick | (event: MouseEvent, src: string, index: number) | 当前容器的图片点击;preventDefault 取消默认预览 |
模板中分别写 @link-click、@image-click。组件不发选择值、change 或预览关闭事件;原生 click、keydown 等按原生属性监听。点击链接中的图片时优先处理图片,默认预览接管同次跳转,不重复发链接通知。
Slots
| 插槽 | 说明 |
|---|---|
| default | 未提供 html 时的真实 Vue 正文;没有作用域参数 |
方法
没有公开实例方法。convertQuillHtml(html: string): string 是从 @nscode/handy-ui/editor 导入的独立格式转换函数,不是组件 ref 方法。
类型
import type {
RichContentProps,
RichContentSanitizeOptions,
RichContentEmits,
RichContentSlots
} from '@nscode/handy-ui/editor'