vue中嵌入原生iframe並傳遞參數

父傳子

// 父頁面main.html傳遞參數

<template>
<div>
<iframe :src="frameUrl" ref="iframe" width="100%" height="100%" frameborder="0" scrolling="auto" @load="loaded"></iframe>
</div>
</template>

<script>
export default {
	name: 'main',
	data(){
		return {			
			frameUrl: '../../../static/child.html',

			params:{
				id:'參數Id',
				name:'參數名稱'
			},
		}
	},
	mounted (){
		var _self=this;
		let myFrame = this.$refs['iframe']
		if (myFrame.attachEvent) { // 兼容瀏覽器判斷
			myFrame.attachEvent('onload', function() {
				const iframeWin = myFrame.contentWindow
				iframeWin.postMessage(_self.params,'*')
			})
		} else {
			myFrame.onload = function() {
				const iframeWin = myFrame.contentWindow
				iframeWin.postMessage(_self.params,'*')
			}
		}	
	},
	methods: {	
		loaded() {
			let vm = this.$refs.iframe.contentWindow.vm
		}
	} 
}
</script>

// 子頁面child.html接收參數
<script>
var id,name;	
window.addEventListener('message', (event) => {				
			id=event.data.id;
			name=event.data.name;
			console.log("我是父頁面傳遞過來的******:"+id+name);
	  })
</script>

子傳父

//child.html子頁面傳參

<script>
window.parent.postMessage({
        params: {
            id: '子頁面Id',
            name:'子頁面名稱'
        }
 }, '*')
</script>

//main.html父頁面接收

<script>
mounted (){
    let id,name;
    window.addEventListener("message", (event) => {				
			id=event.data.id;
			name=event.data.name;
			console.log("******"+id+name);
	  })
}
</script>

參考網址:https://zeyu7.com/vue-iframechuan-zhi/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章