Vue中iframe和组件的通信

最近的项目开发中用到了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)))

 
 

猜你喜欢

转载自www.cnblogs.com/doublewill/p/11802254.html