前言
因为项目需要使用其他封装好的html页面,打算直接使用iframe嵌入,记录下传参时候的问题。
vue端
ref="iframeId"
:src="subUrl"
frameborder="0"
class="iframe"
scrolling="auto"
@load="sendMessage"
>
.iframe {
width: 100%;
height: 100%;
}
export default {
name: "",
data() {
return {
subUrl: "sub.html",
iframe: ""
};
},
mounted() {
this.$nextTick(function() {
this.iframe = this.$refs["iframeId"].contentWindow;
window.addEventListener("message", this.sendMessage);
});
},
destroyed() {
window.removeEventListener("message", this.sendMessage);
},
methods: {
sendMessage() {
this.iframe.postMessage({
data: "传给你个值呀"
},'*');
}
}
sub.html是放到了vue的index.html同级目录
html端
var data;
window.addEventListener('message', function (messageEvent) {
console.log(messageEvent.data)
data = messageEvent.data;
})