vue li实现iframe切换
在 Vue 中使用 <li> 实现 iframe 切换
核心思路:通过 v-for 渲染列表项,动态绑定 iframe 的 src 属性,利用点击事件切换内容。
基础实现步骤
创建数据源存储 iframe 的链接列表,例如:
data() {
return {
iframeLinks: [
{ id: 1, url: 'https://example.com/page1' },
{ id: 2, url: 'https://example.com/page2' }
],
currentIframeUrl: ''
}
}
模板中使用 v-for 渲染导航列表:
<ul>
<li
v-for="link in iframeLinks"
:key="link.id"
@click="currentIframeUrl = link.url">
{{ link.name }}
</li>
</ul>
<iframe :src="currentIframeUrl" width="100%" height="500px"></iframe>
优化交互体验
添加高亮样式标识当前选中项:

<li
v-for="link in iframeLinks"
:class="{ 'active': currentIframeUrl === link.url }"
@click="handleIframeChange(link.url)">
{{ link.name }}
</li>
CSS 样式示例:
.active {
background-color: #42b983;
color: white;
}
动态加载处理
添加加载状态提示:
methods: {
handleIframeChange(url) {
this.isLoading = true;
this.currentIframeUrl = url;
// iframe 的 load 事件可通过 ref 监听
}
}
模板中添加加载指示器:

<iframe
@load="isLoading = false"
v-show="!isLoading">
</iframe>
<div v-if="isLoading">Loading...</div>
安全性增强
对于第三方链接,建议使用 sandbox 属性限制权限:
<iframe
sandbox="allow-same-origin allow-scripts"
:src="currentIframeUrl">
</iframe>
响应式设计建议
通过计算属性控制 iframe 高度:
computed: {
iframeHeight() {
return window.innerHeight - 200 + 'px';
}
}
监听窗口变化:
mounted() {
window.addEventListener('resize', this.handleResize);
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize);
}
这种方法适用于需要快速切换不同内容的场景,如文档预览、多平台对比等场景。注意跨域限制可能导致部分功能不可用。






