likes
comments
collection
share

vue中渲染带script的内容

作者站长头像
站长
· 阅读数 14

vue中渲染带script的内容

问题:

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

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

后端返回的字符串

vue中渲染带script的内容

如果用v-html直接渲染

vue中渲染带script的内容

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

vue中渲染带script的内容

解决方案

使用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标签匹配出来在渲染,需要直接渲染,不然会报错

展示(完美)

vue中渲染带script的内容

解决思路

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

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

3、动态写入iframe(解决)

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