zoukankan      html  css  js  c++  java
  • 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)))

     
     
  • 相关阅读:
    ffmpeg 编译IOS静态库
    冲刺总结——第一篇
    openssl基础知识以及部分命令详解
    电子公文传输系统
    第五组课程设计—小组总结
    学习经验总结
    QtCreator:没CDB二进制档可用为二进制格式在'x86windowsmsvc2008pe32bit'"
    printf格式化输出
    DELL T110 安装windows server 2003
    visualSVN+花生壳实现外网访问局域网内SVN
  • 原文地址:https://www.cnblogs.com/doublewill/p/11802254.html
Copyright © 2011-2022 走看看