vue项目iframe通信
-
父组件传入iframe参数,并接受iframe数据
<template><div><a-button type="primary" @click="sendPostMessage" icon="search">查询</a-button><iframe ref="iframe" style="height: 100%;width: 100%;" :src="editSrc" frameborder="0"id="iframe_dutyOperation"></iframe></div> </template>export default {mounted() {// j接收iframe发送的数据window.addEventListener('message', this.handlerMessage)},methods:{sendPostMessage() {// 获取iframe的window对象let contentWindow = this.$refs.iframe.contentWindowif (!contentWindow) return falsecontentWindow.postMessage({cmd: 'sendParams',params: {template: '',id: ''}}, '*')},handlerMessage(e) {if (e.data.cmd === 'returnData') {console.log(' 传递过来的数据 returnData', e.data)}}}
-
iframe接受数据信息,并返回数据
export default {mounted() {window.addEventListener("message", e => {//监听message 收到数据e.data;if (e.data.cmd === 'sendParams') {console.log('----------', e.data.params);}})},methods:{// 给父组件返回数据sendReturn(){window.parent.postMessage({cmd: 'returnData',params: {state: 200}}, '*');},} }