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>
相关推荐
墨菲安全4 分钟前
NPM组件 @ivy-shared-components/iconslibrary 等窃取主机敏感信息
前端·npm·node.js·npm组件投毒·主机敏感信息窃取·恶意npm包
盛夏绽放39 分钟前
Excel导出实战:从入门到精通 - 构建专业级数据报表的完整指南
开发语言·javascript·excel·有问必答
Mintopia42 分钟前
🌀曲面细分求交:在无限细节中捕捉交点的浪漫
前端·javascript·计算机图形学
Mintopia1 小时前
🧙‍♂️用 Three.js 判断一个点是否在圆内 —— 一次圆心和点的对话
前端·javascript·three.js
liliangcsdn1 小时前
mac mlx大模型框架的安装和使用
java·前端·人工智能·python·macos
CssHero1 小时前
基于vue3完成领域模型架构建设
前端
PanZonghui1 小时前
用项目说话:我的React博客构建成果与经验复盘
前端·react.js·typescript
挽淚1 小时前
JavaScript 数组详解:从入门到精通
javascript
言兴1 小时前
教你如何理解useContext加上useReducer
前端·javascript·面试
sunbyte1 小时前
50天50个小项目 (Vue3 + Tailwindcss V4) ✨ | GoodCheapFast(Good - Cheap - Fast三选二开关)
前端·javascript·css·vue.js·tailwindcss