uniapp处理后台传入的html代码

data.content为后台传入的一段html代码

1.使用v-html

<p class="content" style="width: 100%;" v-html = "data.content">data.content</p>

但是此方法不能控制html中图片的大小

 

2.使用rich-text

<rich-text class="content" id="richId"   :nodes="data.content | formatRichText"></rich-text>

使用过滤器控制图片,表格等

filters: {
            formatRichText(html) { //控制小程序中图片大小
                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:90%;height:auto;display:inline-block;margin:10rpx auto;"');
                // newContent = newContent.replace(/<br[^>]*\/>/gi, '');
                // newContent = newContent.replace(/<td[^<>]*>/ig, '<td style="padding:0px;height:auto;word-break:break-all;">');
                // newContent = newContent.replace(/<td[^<>]*>\s*?<p>/ig, '<td>');
                newContent = newContent.replace(/<table[^>]*>/gi, '<table cellpadding="0" cellspacing="0" max-width="100%" border="1" style="font-size:12px;max-width:100%; text-align:left;text-indent: 0em;line-height:12px;">'); 
                return newContent;
            }
        },

如果想要复制文字可以在类中添加

user-select: text;
-webkit-user-select: text;

但是此方法不支持a标签的href属性,对于后台传入的链接地址可以通过以上代码长按复制,但是对于传入的文件,前台展示的是文件名称,因此无法通过长按复制复制到文件地址

 

3.使用uParse

将uParse的插件包复制到components中,在需要使用的文件中导入

import uParse from '@/components/u-parse/u-parse.vue'

 

<uParse class="content"  :content="data.content | formatRichText"  @longpress="copy" @navigate="navigate" />

方法:

// navigate(href, e) {
// console.log(href,e);
// this.copy(href)
// },

// copy(href){
// uni.setClipboardData({
// data:href,
// success(){
// uni.showToast({
// title:'已复制到剪切板'
// })
// }
// })
// },

 

通过此方法可以复制链接,即可以点击文件名将文件地址复制到剪切板,但是此方法即使使用过滤器,后台传入的表格,展示出来后也是混乱的

 

4.使用mp-html插件

 

使用方法

npm 方式

  1. 在项目根目录下执行
    npm install mp-html

在需要使用页面的 (n)vue 文件中添加

<mp-html :content="html" />
import mpHtml from 'mp-html/dist/uni-app/components/mp-html/mp-html'
export default {
// 不可省略
components: {
 mpHtml
},
data() {
 return {
   html: '<div>Hello World!</div>'
 }
}
}

其他引入方式:https://ext.dcloud.net.cn/plugin?id=805

 

此方法对于表格和文件地址均适用

 

 
posted @ 2022-03-18 13:29  埃菲尔上的加菲猫  阅读(2295)  评论(0编辑  收藏  举报