vue3+ts给iframe传值
时间: 2023-09-14 15:02:34 浏览: 104
在 Vue 3 中,你可以使用 `ref` 来创建一个对 DOM 元素的引用,并使用 `$refs` 来访问它。在 TypeScript 中,你需要使用 `Ref` 类型来定义引用。
以下是一个示例代码,展示如何在 Vue 3 + TypeScript 中使用 `ref` 与 `postMessage` 传递数据给 `iframe`:
```vue
<template>
<iframe ref="myIframe" src="https://example.com"></iframe>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue';
export default defineComponent({
setup() {
const myIframe = ref<HTMLIFrameElement>();
// 发送数据给 iframe
const sendMessage = (data: any) => {
if (myIframe.value) {
myIframe.value.contentWindow?.postMessage(data, '*');
}
};
// 接收来自 iframe 的数据
window.addEventListener('message', (event) => {
console.log('Received message from iframe:', event.data);
});
return {
myIframe,
sendMessage
};
}
});
</script>
```
在上面的代码中,我们创建了一个 `ref` 引用 `myIframe`,并在模板中将其绑定到一个 `iframe` 元素上。然后,我们定义了一个 `sendMessage` 函数,它将数据发送到 `iframe` 中。当 `iframe` 发送消息时,我们在窗口上添加了一个监听器来接收来自 `iframe` 的数据。
阅读全文
相关推荐
![md](https://img-home.csdnimg.cn/images/20250102104920.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://img-home.csdnimg.cn/images/20250102104920.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)