zoukankan      html  css  js  c++  java
  • Vue使用iframe加载本地html,并进行通信,传递参数

    最近做的一个项目,在Vue中要加载本地的html。

    vue cli 3

    文件主目录中包含 public,

    所以首先在 public 文件夹下新建 static 文件夹,

    然后将html文件及相关引用拷贝到static文件夹下。

    在 vue 的文件中添加iframe的对象。

     1 <template>
     2     <iframe
     3         id = "iframe"
     4         ref="frame"
     5         scrolling="no"
     6         frameborder ="0"
     7         width="100%"
     8         :height="height"
     9         v-bind:src = "src"        
    10         @load="onLoad"
    11         >
    12     </iframe>
    13 </template>

    因为项目中要根据菜单点击来加载不同的html文件,

    所以在 onLoad 中根据传递的参数不同,设置不同的 src 参数值, 注意 this.src 赋值的路径,直接写 static ,前面不需要加任何路径和字符

     1 onLoad(frame) {            
     2           console.log(this.page);
     3           let url = 'static/'+ this.page + '.html'; 
     4           console.log(url);
     5           this.src = 'static/'+ this.page + '.html'; 
     6           
     7           if(this.page=="GisMonitor"){
     8             this.height = '99%';
     9           }
    10           this.iframeWindow = this.$refs.frame.contentWindow;
    11         },

    另外在这里添加了与html页面的通信,使用postMessage 传递参数

     1 sendMsg(message){
     2             switch(message){
     3                 case "GisMonitor":
     4                     console.log(this.iframeWindow);
     5                     console.log("Send:"+message)
     6                     this.iframeWindow.postMessage({
     7                         cmd:'GisMonitor',
     8                         params:{"name":"1"}
     9                     },'*');
    10                     break;
    11                 default:
    12                     break;
    13             }
    14         }

    在html页面中,添加监听事件

    1 this.window.addEventListener('message',function (event) {
    2             let dataMessage = event.data;
    3             console.log("Receive:"+ dataMessage);
    4             switch(dataMessage.cmd){
    5                 case "GisMonitor":
    6                     let val = dataMessage.params;
    7                     console.log(val);
    8             }
    9         })
  • 相关阅读:
    HDU 2852 KiKi's K-Number (主席树)
    HDU 2089 不要62
    Light oj 1140 How Many Zeroes?
    Bless You Autocorrect!
    HDU 6201 transaction transaction transaction
    HDU1561 The more ,The better (树形背包Dp)
    CodeForces 607B zuma
    POJ 1651 Mulitiplication Puzzle
    CSUOJ 1952 合并石子
    Uva 1599 Ideal path
  • 原文地址:https://www.cnblogs.com/googlegis/p/15071446.html
Copyright © 2011-2022 走看看