项目场景:
PC端项目、vue技术栈
问题描述
接口数据字段为html片段,页面渲染只需要文字
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/6e4d205331fdf8b0aae70ffb85f8b381.png#pic_center
原因分析:
数据内容可能是从其它的爬取,或者其他项目的页面片段内容
解决方案:
一般有三种解决方案
方案1:v-html指令
在内容区域使用v-html指令(v-html=“字段名称”)
缺陷:不安全,且无法编辑内容的样式
方案2:使用正则表达式
在页面内容区域添加文字样式有效,但是没办法把单独一段文字摘出来,只能添加整体的文字样式
const content = this.content
const regex = />([^<>]+)</g;
const regex2=/ | /g //摘掉$nbsp
const matches = content.matchAll(regex);
const textArray = [...matches].map((match) => match[1]);
this.text = textArray.join("").replace(/[\n\r\s]+/g, '').replace(regex2,'')
console.log(this.text); // "这是一段文字"
const content = this.content
const regex = />([^<>]+)</g;
const regex2=/ | /g //摘掉$nbsp
const matches = content.matchAll(regex);
const textArray = [...matches].map((match) => match[1]);
this.text = textArray.join("").replace(/[\n\r\s]+/g, '').replace(regex2,'')
console.log(this.text); // "这是一段文字"
方案3:使用第三方的插件
百度上有推荐,也可以解决问题,没有做具体尝试,现有项目没有具体用到。