window.open父子页面自定义事件通信

我们在vue项目中,使用vue-router跳转的时候,在某些需求中可以使用router.resolve({path: '/test'}),返回一个返回一个路由地址的规范化版本,其中包含href属性,那我们就可以使用window.open()来打开一个新的浏览器页签跳转至某个vue页面。这篇就是要说一下之间的通信。
例如我从A.vue页面通过window.open跳转至B.vue页面,那么我们称A页面为父页面,B页面为子页面。
我们可以在子页面中通过window.opener拿到父页面的window。当然我们可以使用postMessage进行通信,之前写过一篇关于postMessage的文章(iframe嵌入页面跨域通信),但是这篇不讲postMessage,说一下通过自定义事件的方式来进行父子页面的传值通信。

1. 父传子

1.1 父页面向子页面自定义事件发送数据:

javascript 复制代码
const detail = { source: 'Main' }
window.dispatchEvent(new CustomEvent('mainInfo', { detail }))

1.2 子页面监听父页面事件接受数据:

javascript 复制代码
// 监听父页面自定义事件
window.opener.addEventListener('mainInfo', mainInfo)

function mainInfo(e: any) {
  console.log(e.detail, '接受父页面的数据-->>')
}

2. 子传父

2.1 子页面向父页面自定义事件发送数据:

javascript 复制代码
const detail = { source: 'Test' }
window.opener.dispatchEvent(new CustomEvent('testInfo', { detail }))

2.2 父页面监听子页面事件接受数据:

javascript 复制代码
// 监听子页面自定义事件
window.addEventListener('testInfo', testInfo)

function testInfo(e: any) {
  console.log(e.detail, '接受子页面数据--->>')
}

3. demo

main.vue(父页面)

html 复制代码
<template>
  <div class="main">
    <button @click="toTest">走</button>
    <button @click="sendData">发送数据</button>
  </div>
</template>
<script setup lang="ts">
import { useRouter } from 'vue-router'

const router = useRouter()

const toTest = () => {
  let testUrl = router.resolve({ path: '/test' })
  window.open(testUrl.href, '_blank')
}

// 监听子页面自定义事件
window.addEventListener('testInfo', testInfo)

function testInfo(e: any) {
  console.log(e.detail, '接受子页面数据--->>')
}

// 向子页面发送自定义事件
const sendData = () => {
  const detail = { source: 'Main' }
  window.dispatchEvent(new CustomEvent('mainInfo', { detail }))
}
</script>
<style scoped>
.main {
  width: 100%;
  height: 100%;
}
</style>

test.vue (子页面)

html 复制代码
<template>
  <div class="test">
    <h1>Test</h1>
    <button @click="sendInfo">发送opener</button>
  </div>
</template>
<script setup lang="ts">

// 像父页面发送数据
const sendInfo = () => {
  const detail = { source: 'Test' }
  window.opener.dispatchEvent(new CustomEvent('testInfo', { detail }))
}

// 监听父页面自定义事件
window.opener.addEventListener('mainInfo', mainInfo)

function mainInfo(e: any) {
  console.log(e.detail, '接受父页面的数据-->>')
}
</script>
<style scoped>
.test {
  width: 100%;
  height: 100%;
}
</style>
相关推荐
zwjapple3 小时前
docker-compose一键部署全栈项目。springboot后端,react前端
前端·spring boot·docker
像风一样自由20205 小时前
HTML与JavaScript:构建动态交互式Web页面的基石
前端·javascript·html
aiprtem6 小时前
基于Flutter的web登录设计
前端·flutter
浪裡遊6 小时前
React Hooks全面解析:从基础到高级的实用指南
开发语言·前端·javascript·react.js·node.js·ecmascript·php
why技术6 小时前
Stack Overflow,轰然倒下!
前端·人工智能·后端
幽络源小助理6 小时前
SpringBoot基于Mysql的商业辅助决策系统设计与实现
java·vue.js·spring boot·后端·mysql·spring
GISer_Jing6 小时前
0704-0706上海,又聚上了
前端·新浪微博
止观止6 小时前
深入探索 pnpm:高效磁盘利用与灵活的包管理解决方案
前端·pnpm·前端工程化·包管理器
whale fall6 小时前
npm install安装的node_modules是什么
前端·npm·node.js
烛阴6 小时前
简单入门Python装饰器
前端·python