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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM