vue中渲染带script的内容

1,711 阅读1分钟

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

如果你渲染的字符串内容有带script标签的字符串在.vue项目中会报错

只需要把script标签分开即可

let iframeCon =`<scrip` 
    +`t type="xxxxx" async>
    </s` +`cript>`;