uni-app支付宝小程序中无法显示富文本内容
uni-app支付宝小程序中无法显示富文本内容
| 开发环境 | 版本号 | 项目创建方式 |
|---|---|---|
| Windows | win10 | HBuilderX |
产品分类:uniapp/小程序/阿里
## 示例代码:
```html
<view class="detail" v-if="item.msgType == 'MSG'">
rich-text :nodes="'<div>'+item.context+'</div>'"></rich-text>
<rich-text :nodes="'<b>1111</b>'"></rich-text>
</view>
操作步骤:
必现
预期结果:
显示富文本内容
实际结果:
不显示
bug描述:
rich-text在h5 中可以显示富文本内容,但是在支付宝小程序中无法显示富文本内容
更多关于uni-app支付宝小程序中无法显示富文本内容的实战教程也可以访问 https://www.itying.com/category-93-b0.html
2 回复
支付宝小程序 nodes 属性只支持使用 Array 类型
详见文档https://uniapp.dcloud.io/component/rich-text
更多关于uni-app支付宝小程序中无法显示富文本内容的实战教程也可以访问 https://www.itying.com/category-93-b0.html
在支付宝小程序中,rich-text 组件的 nodes 属性需要传入对象数组,而不是字符串。这与 H5 端的处理方式不同。你需要将 HTML 字符串转换为符合支付宝小程序规范的节点对象数组。
解决方案:
-
安装并引入解析库(如
mp-html): 在项目根目录执行:npm install mp-html在页面中引入:
<template> <mp-html :content="item.context" /> </template> <script> import mpHtml from '@/components/mp-html/mp-html' export default { components: { mpHtml } } </script> -
使用内置的
parse方法(uni-app 自带的节点解析):<template> <rich-text :nodes="parseNodes(item.context)"></rich-text> </template> <script> export default { methods: { parseNodes(html) { // 使用 uni-app 的节点解析 return [{ name: 'div', attrs: { class: 'rich-text' }, children: [{ type: 'text', text: html }] }] } } } </script>注意:这种方式需要手动构建节点树,复杂 HTML 建议用第一种方案。
-
使用条件编译: 如果只需简单文本,可以用条件编译分别处理:
<template> <!-- #ifdef H5 --> <div v-html="item.context"></div> <!-- #endif --> <!-- #ifdef MP-ALIPAY --> <rich-text :nodes="alipayNodes(item.context)"></rich-text> <!-- #endif --> </template>

