vue实现iframe
Vue 中实现 iframe 的方法
在 Vue 项目中,可以通过以下方式实现 iframe 的嵌入和控制:
基本 iframe 嵌入
使用 HTML 的 <iframe> 标签直接嵌入外部页面:
<template>
<iframe
src="https://example.com"
width="100%"
height="500px"
frameborder="0"
></iframe>
</template>
动态绑定 iframe 属性
通过 Vue 的数据绑定实现动态 URL 和属性:
<template>
<iframe
:src="iframeUrl"
:width="width"
:height="height"
frameborder="0"
></iframe>
</template>
<script>
export default {
data() {
return {
iframeUrl: 'https://example.com',
width: '100%',
height: '500px'
}
}
}
</script>
父子通信
通过 postMessage 实现 iframe 与父页面的通信:

父页面代码:
<template>
<iframe
ref="myIframe"
src="https://example.com"
@load="onIframeLoad"
></iframe>
</template>
<script>
export default {
methods: {
onIframeLoad() {
const iframe = this.$refs.myIframe;
iframe.contentWindow.postMessage('Hello from parent', '*');
}
},
mounted() {
window.addEventListener('message', (event) => {
if (event.origin !== 'https://example.com') return;
console.log('Message from iframe:', event.data);
});
}
}
</script>
iframe 页面代码:

window.addEventListener('message', (event) => {
if (event.origin !== 'https://parent-domain.com') return;
console.log('Message from parent:', event.data);
event.source.postMessage('Hello from iframe', event.origin);
});
安全性考虑
添加 sandbox 属性限制 iframe 权限:
<iframe
src="https://example.com"
sandbox="allow-same-origin allow-scripts allow-popups"
></iframe>
响应式 iframe
使用 CSS 实现响应式 iframe:
<template>
<div class="iframe-container">
<iframe
src="https://example.com"
frameborder="0"
></iframe>
</div>
</template>
<style>
.iframe-container {
position: relative;
overflow: hidden;
padding-top: 56.25%; /* 16:9 Aspect Ratio */
}
.iframe-container iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
border: 0;
}
</style>
懒加载 iframe
实现 iframe 的懒加载:
<template>
<iframe
v-if="showIframe"
src="https://example.com"
></iframe>
<button @click="showIframe = true">Load Iframe</button>
</template>
<script>
export default {
data() {
return {
showIframe: false
}
}
}
</script>
这些方法涵盖了 Vue 中使用 iframe 的常见场景,包括基本嵌入、动态控制、通信、安全性和响应式设计等方面。






