iframe页面向vue父页面传值,vue页面向iframe页面传值

1.iframe页面向vue父页面传值
vue代码

<template>
	<div>
		<iframe id="iframe"></iframe>
	</div>
</template>
<script>
	export default { 
		data(){
			return {
				iframeData: null
			}
		},
		mounted(){
			let that = this;
	        window.addEventListener("message", function(e) {
		         that.iframeData = e.data
		    });
		}
	}
</script>

iframe代码

<script>
	let message = 1;
    window.parent.postMessage(message,"*");
</script>

2.vue页面向iframe页面传值
vue代码

<template>
	<div>
		<iframe id="iframe" ref="iframe"></iframe>
	</div>
</template>
<script>
	export default { 
		mounted(){
			this.iframe = this.$refs.iframe
      		this.iframeWindow = this.iframe.contentWindow
      		let message = 1
      		this.iframeWindow.postMessage(message, '*')
		}
	}
</script>

iframe代码

<script>
	window.addEventListener('message', function (e) {
		console.log(e.data)
	}        
</script>
  • 1
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
由于浏览器的安全限制,Vue页面无法直接向嵌套的iframe中的html页面传值。但是可以通过以下方式实现: 1. 使用postMessage 在Vue页面中使用postMessage向iframe发送消息,iframe中的html页面监听message事件,接收消息并进行处理。 Vue页面: ```javascript // 发送消息到iframe const iframeWindow = document.getElementById('iframe').contentWindow; iframeWindow.postMessage({data: 'hello'}, '*'); // 监听iframe返回的消息 window.addEventListener('message', (event) => { if (event.origin !== 'http://iframe-origin.com') return; // 验证消息来源 console.log(event.data); // 处理返回的消息 }); ``` iframe页面: ```javascript // 监听消息 window.addEventListener('message', (event) => { if (event.origin !== 'http://vue-origin.com') return; // 验证消息来源 console.log(event.data); // 处理接收到的消息 }); // 发送消息到Vue页面 const parentWindow = window.parent; parentWindow.postMessage({data: 'world'}, 'http://vue-origin.com'); ``` 2. 使用URL参数 在Vue页面中嵌套iframe时,可以在iframe的src属性中添加参数,iframe中的html页面可以通过URL参数获取传递的值。 Vue页面: ```html <iframe src="http://iframe-origin.com?data=hello"></iframe> ``` iframe页面: ```javascript // 获取URL参数 const urlParams = new URLSearchParams(window.location.search); const data = urlParams.get('data'); console.log(data); // 处理获取到的值 ``` 需要注意的是,使用URL参数传递数据时,需要考虑参数的安全性,避免出现安全漏洞。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值