vue iframe 实现tab
使用 Vue 和 iframe 实现 Tab 功能
在 Vue 中通过 iframe 实现 Tab 功能,可以结合动态组件或路由来实现多标签页的切换效果。以下是具体实现方法:
动态 iframe 切换
通过 v-if 或动态组件控制不同 iframe 的显示与隐藏,结合 Tab 标题实现切换逻辑。
<template>
<div>
<div class="tabs">
<button
v-for="(tab, index) in tabs"
:key="index"
@click="currentTab = index"
:class="{ active: currentTab === index }"
>
{{ tab.title }}
</button>
</div>
<div class="iframe-container">
<iframe
v-for="(tab, index) in tabs"
:key="index"
v-show="currentTab === index"
:src="tab.url"
frameborder="0"
></iframe>
</div>
</div>
</template>
<script>
export default {
data() {
return {
currentTab: 0,
tabs: [
{ title: 'Google', url: 'https://www.google.com' },
{ title: 'Baidu', url: 'https://www.baidu.com' },
{ title: 'GitHub', url: 'https://github.com' }
]
};
}
};
</script>
<style>
.tabs button {
padding: 8px 16px;
margin-right: 4px;
cursor: pointer;
}
.tabs button.active {
background-color: #42b983;
color: white;
}
.iframe-container {
width: 100%;
height: 500px;
}
iframe {
width: 100%;
height: 100%;
}
</style>
结合 Vue Router
若需通过路由管理 Tab,可以使用嵌套路由或动态路由参数。
<template>
<div>
<router-link
v-for="(tab, index) in tabs"
:key="index"
:to="tab.path"
custom
v-slot="{ navigate }"
>
<button @click="navigate" :class="{ active: $route.path === tab.path }">
{{ tab.title }}
</button>
</router-link>
<router-view></router-view>
</div>
</template>
<script>
export default {
data() {
return {
tabs: [
{ title: 'Google', path: '/google' },
{ title: 'Baidu', path: '/baidu' }
]
};
}
};
</script>
路由配置示例(需在 router.js 中定义):
const routes = [
{
path: '/google',
component: () => import('./components/GoogleIframe.vue')
},
{
path: '/baidu',
component: () => import('./components/BaiduIframe.vue')
}
];
动态加载 iframe 的组件
为每个 Tab 创建独立的组件,通过 component :is 动态加载。
<template>
<div>
<button
v-for="(tab, index) in tabs"
:key="index"
@click="currentTab = tab.component"
:class="{ active: currentTab === tab.component }"
>
{{ tab.title }}
</button>
<component :is="currentTab"></component>
</div>
</template>
<script>
import GoogleIframe from './GoogleIframe.vue';
import BaiduIframe from './BaiduIframe.vue';
export default {
components: { GoogleIframe, BaiduIframe },
data() {
return {
currentTab: 'GoogleIframe',
tabs: [
{ title: 'Google', component: 'GoogleIframe' },
{ title: 'Baidu', component: 'BaiduIframe' }
]
};
}
};
</script>
注意事项
- 跨域限制:iframe 加载外部 URL 可能受浏览器同源策略限制,部分网站会禁止嵌套。
- 性能优化:频繁切换 iframe 可能导致内存占用过高,可考虑使用
v-show替代v-if减少重渲染。 - 通信需求:若需与 iframe 内页面交互,需通过
postMessage实现跨域通信。







