uniapp富文本组件
uniapp富文本组件使用指南
uniapp提供了多种方式实现富文本渲染,以下是常用的方法和组件:
uni-app内置rich-text组件
uniapp内置的rich-text组件可以解析HTML字符串并渲染为富文本:
<template>
<rich-text :nodes="htmlString"></rich-text>
</template>
<script>
export default {
data() {
return {
htmlString: '<div style="color: red;">红色文本</div><p>段落文本</p>'
}
}
}
</script>
uParse插件方案
对于更复杂的富文本需求,可以使用社区插件uParse:
-
安装uParse插件
npm install @/components/gaoyia-parse -
在页面中使用
<template> <gaoyia-parse :content="htmlContent"></gaoyia-parse> </template>
标题
第三方富文本编辑器集成
对于需要编辑功能的场景,可集成第三方编辑器:
-
微信小程序可使用editor组件
<editor id="editor" @input="onInput"></editor> -
H5端可使用wangEditor或Quill
// 在mounted生命周期中初始化 mounted() { if(process.env.VUE_APP_PLATFORM === 'h5') { const editor = new WangEditor('#editor') editor.create() } }
富文本内容安全处理
处理富文本时需注意XSS防护:
// 使用xss过滤库
import xss from 'xss'
const safeHtml = xss(unsafeHtmlString)
图片自适应处理
富文本中的图片需要特殊处理以适应不同屏幕:
/* 全局样式 */
rich-text img {
max-width: 100%;
height: auto;
}
平台差异说明
- 微信小程序:rich-text支持大部分HTML标签
- H5:完全支持HTML
- App:部分CSS样式需要额外处理
通过以上方法可以实现uniapp中的富文本展示需求,根据具体场景选择合适的方案。






