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'