最近的項目開發中用到了Vue組件中嵌套iframe,相應的碰到了組件和HTML的通信問題,場景如下:demo.vue中嵌入 test.html
由於一般的iframe嵌套是用於HTML文件的,在vue中我們需要在vue文件注冊一個全局的方法,在iframe中某個事件觸發時,可以回傳到vue組件
demo.vue主要代碼:
<template>
<iframe ref="iframe" src='test.html'> </iframe>
</template>
<script>
export default {
data() {
return {
spanClick: 'handleSpanClick' //html中需要響應的事件
}
},
created() {
let _this = this
window[this.spanClick] = (params) => {
_this.doSomeThing(params)
}
},
methods: {
doSomeThing(params){
//todo
}
}
}
</script>
test.html主要代碼;
<div>
<span onclick="handleTest(this)">test</span>
</div>
<script>
function handleTest(event) {
window.parent['handleSpanClick'](event.innerText)
}
<script>
有的時候,我們需要從vue組件中向html傳參,一種比較簡單的方法是在iframe的src中做拼接,舉個栗子,我們需要在vue中向HTML傳入一個json
data = {
id: 1,
name: 'will'
}
這時候的src = ‘test.html?’ + encodeURIComponent(JSON.stringify(data)) //使用encodeURIComponent 是為了在傳參的時候對參數加密一下防止亂碼
相應的在test.html中需要解碼:
JSON.parse(decodeURIComponent(window.location.search.slice(1)))