Skip to content

Parse 富文本解析

介绍

用于解析并渲染富文本(HTML),支持段落、标题、列表、链接、图片、引用等常见标签,可通过 tagStyleclassStyle 自定义标签与类名样式,适用于文章详情、用户生成内容等场景。

导入

js
import Parse from '@/components/display/parse/Parse.vue'

用法

基础用法

传入 content 为 HTML 字符串即可渲染,支持加粗、斜体、链接、标题、列表、图片、引用等。

vue
<template>
  <Parse :content="htmlBasic" />
</template>

<script setup>
const htmlBasic = `
<p>这是一段<strong>加粗</strong>和<em>斜体</em>的富文本,支持 <a href="https://example.com">链接</a>。</p>
<p>支持标题:</p>
<h3>三级标题</h3>
<p>以及列表:</p>
<ul>
  <li>列表项一</li>
  <li>列表项二</li>
  <li>列表项三</li>
</ul>
<p>以及图片</p>
<img src="https://imengyu.top/assets/images/test/1.jpg" />
<blockquote>这是一段引用块内容。</blockquote>
`;
</script>

完整标签

组件支持常见 HTML 标签,包括文本样式(加粗、斜体、下划线、删除线、大小号)、标题 h1~h6、无序/有序列表(含嵌套)、表格、图片、引用等。

vue
<template>
  <Parse
    :content="htmlFull"
    :class-style="{
      'section-title': 'font-size: 18px; font-weight: 500; margin: 1.5rem 0 0.8rem; color: #1967d2; border-left: 3px solid #1967d2; padding-left: 0.8rem;'
    }"
  />
</template>

可根据内容中的 class 使用 classStyle 为指定类名设置样式,键为类名,值为 CSS 字符串。

自定义标签样式

通过 tagStyle 为指定标签名设置样式,键为标签名(如 h4pblockquote),值为 CSS 字符串。

vue
<template>
  <Parse :content="htmlWithStyle" :tag-style="tagStyle" />
</template>

<script setup>
const htmlWithStyle = `
<p>通过 tagStyle 可自定义各标签的样式。</p>
<h4>自定义标题颜色</h4>
<p>段落与<mark>高亮</mark>、<code>代码</code>样式。</p>
`;

const tagStyle = {
  h4: 'color: #1989fa; font-size: 18px;',
  p: 'color: #333; line-height: 1.6;',
  blockquote: 'border-left-color: #1989fa; background: #f0f8ff;',
};
</script>

容器样式

通过 contentStyle 设置富文本根容器的样式,适用于内边距、背景、圆角等布局与装饰。

vue
<template>
  <Parse
    content="<p>容器设置了内边距与浅色背景。</p><p>适用于需要与周围留出间距的场景。</p>"
    :content-style="{ padding: '24rpx', backgroundColor: '#a8f8f8', borderRadius: '12rpx' }"
  />
</template>

API 参考

Parse

富文本解析组件,将 HTML 字符串解析为节点树并渲染。

Props

名称说明类型必填默认值
content要解析的 HTML 内容string | null | undefined--
tagStyle按标签名设置样式,键为标签名,值为 CSS 字符串Record<string, string>-{}
classStyle按 class 设置样式,键为类名,值为 CSS 字符串Record<string, string>-{}
contentStyle根容器样式object-{}

类型说明

组件内部将 HTML 解析为 ParseNode 节点树,类型定义位于 @/components/display/parse/Parse.ts,包含 tagattrschildrenparentTagindex 等字段,供扩展或二次渲染时参考。