vue中渲染带script的内容

vue中渲染带script的内容

问题:

1、项目为Vue2,后端返回了带script标签的内容,需要前端去展示,用v-html直接去渲染,失效

2、渲染一个动态内容,后端返回一个内容为html的字符串(类似富文本),这个内容中的script 包含一些方法

后端返回的字符串

image-20221201171817212.png

如果用v-html直接渲染

image-20221201172023914.png

不多说,上图(后端返回字段预览的效果)

image-20221201171517040.png

解决方案

使用ifram,附上代码

html结构

 <iframe id="iframe" width="100%" height="600" v-show="detail.templateType"></iframe>

js

this.$http(params).then((res) => {
    //拿到后端接口请求过来的数据
this.detail = res.data;
    //这是我自己的业务逻辑要求
    if (this.detail.templateType) {
let iframe = document.getElementById("iframe");
let iframedoc =iframe.contentDocument ||iframe.contentWindow.document;
iframedoc.write(this.detail.content);
}
}
杜绝问题:

不能通过匹配把script标签匹配出来在渲染,需要直接渲染,不然会报错

展示(完美)

image-20221201184225148.png

解决思路

1、v-html、innerHtml、append:无法识别script标签

2、 iframe:无法直接渲染这种字符串

3、动态写入iframe(解决)

4、风险预估,附上文档write

© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容