vue实现frame
Vue 中实现 iframe 的方法
在 Vue 中可以通过以下方式实现 iframe 的嵌入和控制:
基本 iframe 嵌入
<template>
<iframe src="https://example.com" frameborder="0"></iframe>
</template>
动态绑定 iframe 属性
<template>
<iframe
:src="iframeSrc"
:width="iframeWidth"
:height="iframeHeight"
frameborder="0"
></iframe>
</template>
<script>
export default {
data() {
return {
iframeSrc: 'https://example.com',
iframeWidth: '100%',
iframeHeight: '500px'
}
}
}
</script>
监听 iframe 加载事件
<template>
<iframe
src="https://example.com"
@load="onIframeLoad"
ref="myIframe"
></iframe>
</template>
<script>
export default {
methods: {
onIframeLoad() {
console.log('iframe loaded');
// 可以在这里访问 iframe 内容
const iframeDoc = this.$refs.myIframe.contentDocument;
}
}
}
</script>
安全注意事项
- 同源策略限制:iframe 内容与父页面不同源时,无法直接访问 iframe 内部 DOM
- 使用 postMessage 进行跨域通信
- 添加 sandbox 属性增强安全性
与 iframe 通信示例
父页面:
// 向 iframe 发送消息
window.frames[0].postMessage('hello', 'https://iframe-domain.com');
iframe 内:
// 接收父页面消息
window.addEventListener('message', (event) => {
if (event.origin !== 'https://parent-domain.com') return;
console.log('Received message:', event.data);
});
Vue 组件封装 iframe
可以创建可复用的 iframe 组件:
<!-- IframeComponent.vue -->
<template>
<iframe
:src="src"
:title="title"
:style="iframeStyle"
@load="handleLoad"
ref="iframe"
></iframe>
</template>
<script>
export default {
props: {
src: String,
title: String,
width: {
type: String,
default: '100%'
},
height: {
type: String,
default: '500px'
}
},
computed: {
iframeStyle() {
return {
width: this.width,
height: this.height,
border: 'none'
}
}
},
methods: {
handleLoad() {
this.$emit('loaded');
}
}
}
</script>
使用组件:

<iframe-component
src="https://example.com"
title="Example Site"
@loaded="handleIframeLoad"
/>






