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>
相关推荐
遇到困难睡大觉哈哈3 小时前
Harmony os 静态卡片(ArkTS + FormLink)详细介绍
前端·microsoft·harmonyos·鸿蒙
用户47949283569153 小时前
Bun 卖身 Anthropic!尤雨溪神吐槽:OpenAI 你需要工具链吗?
前端·openai·bun
p***43483 小时前
前端在移动端中的网络请求优化
前端
g***B7383 小时前
前端在移动端中的Ionic
前端
大猩猩X4 小时前
vxe-gantt 甘特图使用右键菜单
vue.js·vxe-table·vxe-ui·vxe-gantt
拿破轮4 小时前
使用通义灵码解决复杂正则表达式替换字符串的问题.
java·服务器·前端
whltaoin4 小时前
【 Web认证 】Cookie、Session 与 JWT Token:Web 认证机制的原理、实现与对比
前端·web·jwt·cookie·session·认证机制
Aerelin4 小时前
爬虫playwright入门讲解
前端·javascript·html·playwright
笙年5 小时前
JavaScript Promise,包括构造函数、对象方法和类方法
开发语言·javascript·ecmascript
桜吹雪5 小时前
LangChain.js/DeepAgents可观测性
javascript·人工智能