申请注意事项:详见https://mp.weixin.qq.com/wxopen/plugindevdoc?appid=wxa51b9c855ae38f3c&token=&lang=zh_CN#-
解析部分标签,dom片段
在全局app.vue(我这里是用hbuilderx启动的项目所以是app.vue中,开发者工具中是main.js)中封装一个函数对数据结构进行处理
formatRichText(html) {
// store_source_id 为1是平台的,2是享库存,3是联联,3需要其他方式去解析
let newContent = html.replace(/<img[^>]*>/gi, function(match, capture) {
match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
return match;
});
newContent = newContent.replace(/style="[^"]+"/gi, function(match, capture) {
match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
return match;
});
newContent = newContent.replace(/<br[^>]*\/>/gi, '');
newContent = newContent.replace(/\<img/gi,
'<img style="max-width:100%;height:auto;display:inline-block;margin:10rpx auto;"');
return newContent;
},
页面中使用
<view class="detailCon lists" v-if="setmeal">
<view class="title">套餐详情</view>
<view class="content content_html" v-html="setmeal "></view>
</view>
//接口请求成功后返回的数据
const data = res.data
this.setmeal = data.setmeal
if(this.setmeal){
this.setmeal= app.formatRichText(this.setmeal);
if(this.setmeal.charAt(this.setmeal.length-1)!=">"){
this.setmeal=this.setmeal+'"/>'
}
}
解析整个html文件
(1)打开小程序后台
(2)搜索html2wxml插件并添加
(3)等待通过后点击详情查看appid(此appid不是你开发者的appid)
(4)回到hbuilderx中在pages.json文件中添加如下代码(微信开发者工具则是在app.json中添加)
根据最新的版本来,我这会用的时候是1.4.0
"plugins": {
"htmltowxml": {
"version": "1.4.0",
"provider": "wxa51b9c855ae38f3c"
}
}
(5)在小程序对应页面的json文件中添加(hbuilderx中则是在pages.json文件中对应的页面路径的style中添加)
"usingComponents": {
"htmltowxml": "plugin://htmltowxml/view"
}
hbuilderx中
(6)直接在页面给变量赋值,展示即可
<htmltowxml text="{
{spdetailInfo}}" showLoading="false"></htmltowxml>
//详情属性见下一步详细介绍
this.spdetailInfo = res.data.detail
组件使用方法如下
示例代码
// 将Page中的content数据作为HTML格式渲染
<htmltowxml text="{
{content}}" bindWxmlTagATap="wxmlTagATap" />
// 禁用代码高亮功能
<htmltowxml text="{
{content}}" highlight="{
{false}}" bindWxmlTagATap="wxmlTagATap" />
// 禁用代码行号显示功能
<htmltowxml text="{
{content}}" linenums="{
{false}}" bindWxmlTagATap="wxmlTagATap" />
// 代码高亮样式改为tomorrow
<htmltowxml text="{
{content}}" highlightStyle="tomorrow" bindWxmlTagATap="wxmlTagATap" />
// 设置代码高亮检测语言 (最多6个,自行搭建服务不受限制)
<htmltowxml text="{
{content}}" highlightLanguages="{
{['html','js','php','css','cpp','ruby']}}" bindWxmlTagATap="wxmlTagATap" />
// 对HTML数据中的img标签的相对路径补全域名
<htmltowxml text="{
{content}}" imghost="https://www.qwqoffice.com" bindWxmlTagATap="wxmlTagATap" />
// 禁用加载中动画
<htmltowxml text="{
{content}}" showLoading="{
{false}}" bindWxmlTagATap="wxmlTagATap" />
// 将Page中的text数据作为Markdown格式渲染
<htmltowxml text="{
{text}}" type="md" bindWxmlTagATap="wxmlTagATap" />
// 直接渲染Page中的已经过解析的obj数据
<htmltowxml json="{
{obj}}" bindWxmlTagATap="wxmlTagATap" />