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 方式
- 在項目根目錄下執行
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
此方法對於表格和文件地址均適用