先去下载wxParse对应的文件,引入方式这里不介绍了。
wxParse代码仓库:https://github.com/icindy/wxParse
//第一步:小程序js中的data数据
js引入对应js:
var WxParse = require('../../components/wxParse/wxParse.js');//路径根据本地自己引入的文件
data: {
// 用来模拟接口请求到的数据
newData: [
{
id: 1,
title:'第一条',
content: '<h1>这里是第一条数据这里是第一条数据这里是第一条数据这里是第一条数据这里是第一条数据这里是第一条数据</h1>',
time: '2019-08-08',
},
{
id: 2,
title: '第二条',
content: '<div>这里是第二条这里是第二条这里是第二条这里是第二条这里是第二条</div>',
time: '2019-08-08',
},
{
id: 3,
title: '第三条',
content: '这里是第三条这里是第三条这里是第三条这里是第三条这里是第三条这里是第三条这里是第三条这里是第三条',
time: '2019-08-08',
},
],
msgArr:[],//列表中渲染数据的数组
msgListArr:[],//这个用来接收每次请求到的数据叠加数组(重要用于上拉加载更多,多次请求)
},
二、自定义一个方法模拟请求接口
//获取需要解析数据 parseArrData:function(){ let that = this; let newData = that.data.newData; let msgListArr = that.data.msgListArr; for (let i = 0; i < newData.length; i++) { WxParse.wxParse('content' + i, 'html', newData[i].content, that); //delete newData[i].content; if (i === newData.length - 1) { WxParse.wxParseTemArray("WxParseListArr", 'content', newData.length, that); } } console.log(newData); console.log(that.data.WxParseListArr); let listArr = that.data.WxParseListArr; listArr.forEach((item,index)=>{ newData[index].contentCopy = item; msgListArr.push(newData[index]) }) console.log('newData',newData) console.log('msgListArr',msgListArr) that.setData({ msgArr: msgListArr }) }
三、视图页面中进行渲染
<import src="../../components/wxParse/wxParse.wxml" /> <view> <block wx:for="{{msgArr}}" wx:for-item="news" wx:key="unique"> <view class='newsList' bindtap="msgDetailTap" data-item="{{news}}"> <view class="newsTitle"> <view class="newsTitleName">{{news.title}} </view> <view class='newsDate'>{{news.time}}</view> </view> <view class='newsText pd20 content'> <template is="wxParse" data="{{wxParseData:news.contentCopy}}" /> </view> <!-- <view class='newsDate pd20'>{{news.start_time_at}}</view> --> </view> </block> </view>
四、页面中css
.newsList{ margin: 20rpx; background-color: #FFF; border-radius: 16rpx; color: #333; font-size: 28rpx; padding: 0 20rpx; } .pd20{ padding: 20rpx 0; } .newsDate{ color: #999; font-size: 24rpx;line-height: 34rpx; } .newsText{ /* line-height: 40rpx; */ padding-bottom: 30rpx; /* height: 120rpx; */ } .pB0{ padding-bottom: 0px; } .newsTitle{ color: #333; font-size: 32rpx; padding: 20rpx 0; border-bottom: solid 2rpx #F5F5F5; display: flex; align-items: center; justify-content: space-between; } .lH40{ line-height: 40rpx; } .goods-details-content{ margin: 0; letter-spacing: 4rpx; } .newsTitleName{ width: 420rpx; overflow:hidden; text-overflow:ellipsis; white-space: nowrap; font-weight: 400; }
就这样实现了数组富文本解析。如果对您有帮助,请点个赞!!!
谢谢!!!