服务端同学返回了这样的数据:
scene: "<p>通用</p>↵"
需要将scene字段解析出来,将“通用”二字正确地渲染出来。当然,上述只是一个demo,服务端返回的数据中包括了所有html标签,以及相应的样式。
因此在vue项目中采用了v-html指令来实现。
关于v-html指令,vue官网给出了这样的解释:
毫无疑问,我在使用的过程中,是有警告的
warning 'v-html' directive can lead to XSS attack vue/no-v-html
针对上述告警,我查了相关资料,试图去解决,搜到这篇文章,感觉写的不错,介绍了原理及解决方案。
解决v-html指令潜在的xss攻击文章链接:https://blog.csdn.net/lingxiaoxi_ling/article/details/105851736
还有其他几种解决方案,我没有尝试,大家可以试一下,咱们一起交流:
vue项目前端解决xss攻击方案:https://blog.csdn.net/baogeprh/article/details/111216064
但比较遗憾的是我采用上述方案,并没有成功,因此放弃了v-html指令实现方式,采用了其他方案。
<p ref='questionDescription' class='image-style'></p>
this.$refs.questionDescription.innerHTML = this.detailInfo.description;
其中上述类image-style,是用来修改返回的数据中,图片的样式的。
这就涉及到一个点,更改v-html的样式,这里虽然没用v-html,但是修改样式的原理是一样的。这篇文章写的不错:https://blog.csdn.net/xh1506101064/article/details/106675796
最终我是这样处理的样式:
<style lang='less' scoped>
.image-style {
/deep/ img{
width: 100% !important;
height: 100% !important;
}
}
</style>
另外,采用第三方插件vue-dompurity-html也是可以实现的,具体链接:https://www.npmjs.com/package/vue-dompurify-html