看啥推荐读物
专栏名称: 夜雨风亭
目录
相关文章推荐
今天看啥  ›  专栏  ›  夜雨风亭

vue打开其他项目页面,并传入数据

夜雨风亭  · CSDN  ·  · 2020-11-17 18:16

1.不跨域,携带sessionstorage打开

主页面,存储sessionstorage后,打开页面

let data = {
	text:'我是数据'
};
let isMobile = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)?true:false;

sessionStorage.setItem('information',JSON.stringify(data));
//ios不能打开新窗口,所以改为移动端在原本页面打开,pc打开新窗口
window.open(window.location.protocol + "//" + window.location.host + reportUrl, isMobile?'_self':'_blank');
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

子页面

var date = JSON.parse(sessionStorage.getItem('information'));
  • 1
  • 1

2.跨域,iframe通信

跨域的情况下,无法携带sessionstorage,通过iframe的postMessage通信机制传递数据;
不跨域也可以用,但更建议使用第一种,比较丝滑~

主页面,写入url,加载完成后,发送数据

<iframe id='iframe' class="iframe" v-if="src" ref="iframe" :src="src"></iframe>

let data = {
	text:'我是数据'
};
this.src = url
this.$nextTick(()=>{
	document.getElementById('iframe').onload=()=>{
		document.getElementById('iframe').contentWindow.postMessage({
			type:'preview',
			data:data
		},this.src)
		document.getElementById('iframe').onload=null;
    }
})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

子页面,执行监听,created、mounted都可以

created() {
	window.addEventListener('message',(event)=>{
	      console.log(event.data.type)
	      if(event.data&&event.data.type=='preview'){
	            console.log(event.data.data)
	            let data = JSON.stringify(event.data.data)
	      }
	 }, false);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9



原文地址:访问原文地址
快照地址: 访问文章快照