Vue使⽤iframe加载本地html,并进⾏通信,传递参数
最近做的⼀个项⽬,在Vue中要加载本地的html。
vue cli 3
⽂件主⽬录中包含 public,
所以⾸先在 public ⽂件夹下新建 static ⽂件夹,
然后将html⽂件及相关引⽤拷贝到static⽂件夹下。
在 vue 的⽂件中添加iframe的对象。
1<template>
2<iframe
3id = "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);
5this.src = 'static/'+ this.page + '.html';
6
7if(this.page=="GisMonitor"){
8this.height = '99%';
9          }
10this.iframeWindow = this.$tWindow;
11        },
另外在这⾥添加了与html页⾯的通信,使⽤postMessage 传递参数
1 sendMsg(message){
2switch(message){
3case "GisMonitor":
4                    console.log(this.iframeWindow);
5                    console.log("Send:"+message)
6this.iframeWindow.postMessage({
7                        cmd:'GisMonitor',iframe参数传递
8                        params:{"name":"1"}
9                    },'*');
10break;
11default:
12break;
13            }
14        }
在html页⾯中,添加监听事件
1this.window.addEventListener('message',function (event) {
2            let dataMessage = event.data;
3            console.log("Receive:"+ dataMessage);
d){
5case "GisMonitor":
6                    let val = dataMessage.params;
7                    console.log(val);
8            }
9        })