vue实现iframe跳转
在Vue中实现iframe跳转
通过Vue动态绑定iframe的src属性实现跳转,核心是利用v-bind或简写:控制<iframe>的源地址。
<template>
<div>
<iframe :src="currentUrl" frameborder="0"></iframe>
<button @click="changeUrl('https://example.com')">跳转示例网站</button>
</div>
</template>
<script>
export default {
data() {
return {
currentUrl: ''
}
},
methods: {
changeUrl(newUrl) {
this.currentUrl = newUrl
}
}
}
</script>
父子组件通信方式
若iframe位于子组件中,可通过props传递URL实现跳转控制:
<!-- 父组件 -->
<template>
<ChildComponent :iframeUrl="targetUrl" />
</template>
<!-- 子组件 -->
<template>
<iframe :src="iframeUrl"></iframe>
</template>
<script>
export default {
props: ['iframeUrl']
}
</script>
跨域通信处理
当需要与iframe内页面交互时,使用window.postMessage:
// 父窗口发送消息
iframe.contentWindow.postMessage('data', '*')
// 子窗口接收消息
window.addEventListener('message', (event) => {
if (event.origin !== 'https://trusted-domain.com') return
console.log(event.data)
})
动态加载优化
为避免重复加载iframe,可采用v-if控制显隐:
<button @click="showIframe = true">显示iframe</button>
<iframe v-if="showIframe" src="https://example.com"></iframe>
安全注意事项
-
使用
sandbox属性限制iframe权限:<iframe sandbox="allow-scripts allow-same-origin"></iframe> -
验证动态URL的合法性,防止XSS攻击:
if (!url.startsWith('https://trusted-domain')) return -
对于用户输入生成的URL,务必进行转义处理







