vue实现frame
Vue 中实现 iframe 的方法
在 Vue 中可以通过直接使用 <iframe> 标签或动态绑定 src 属性来实现 iframe 功能。
基本用法
<template>
<iframe src="https://example.com" frameborder="0"></iframe>
</template>
动态绑定 src
<template>
<iframe :src="iframeUrl" frameborder="0"></iframe>
</template>
<script>
export default {
data() {
return {
iframeUrl: 'https://example.com'
}
}
}
</script>
控制 iframe 高度自适应
通过监听窗口大小变化或内容加载完成事件,可以动态调整 iframe 高度。

<template>
<iframe
ref="myIframe"
:src="iframeUrl"
@load="adjustHeight"
frameborder="0"
style="width: 100%"
></iframe>
</template>
<script>
export default {
methods: {
adjustHeight() {
const iframe = this.$refs.myIframe
iframe.style.height = iframe.contentWindow.document.body.scrollHeight + 'px'
}
}
}
</script>
父子页面通信
使用 postMessage API 实现 iframe 内外通信。
父页面发送消息

// 在 Vue 组件中
const iframe = document.getElementById('my-iframe')
iframe.contentWindow.postMessage('Hello from parent', '*')
子页面接收消息
// 在 iframe 页面中
window.addEventListener('message', (event) => {
console.log('Received message:', event.data)
})
安全性考虑
使用 iframe 时需要注意以下安全事项:
- 始终验证跨域消息来源
- 使用
sandbox属性限制 iframe 权限 - 避免加载不可信来源的内容
<iframe
src="https://example.com"
sandbox="allow-same-origin allow-scripts"
></iframe>
响应式设计技巧
结合 Vue 的响应式特性,可以创建更灵活的 iframe 组件:
<template>
<div class="iframe-container">
<iframe
:src="url"
:title="title"
@load="onLoad"
></iframe>
</div>
</template>
<script>
export default {
props: {
url: String,
title: String
},
methods: {
onLoad() {
this.$emit('loaded')
}
}
}
</script>
<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>






