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)))

     
     
  • 相关阅读:
    c++ 输出 变量名 字符串(zz.is2120.BG57IV3)
    分页存储过程
    连接字符串
    动软 DBHeper 完全代码
    java 数据库连接字符串
    DOS命令行下常见的错误信息
    点击单元格选择整行,又可编辑单元格
    label里文字中的下划线
    Delphi程序中动态生成控件的方法及应用
    双击dbgrid排序的问题
  • 原文地址:https://www.cnblogs.com/doublewill/p/11802254.html
Copyright © 2011-2022 走看看