vue嵌套iframe
- 创建 iframe 通用组件
- 添加页面及路由
- 进阶:vue 与 iframe 的双向通讯
- 代码下载
适用于使用vue重构及vue访问其他服务页面
基于vue3示例页面添加嵌套
iframe
的页面
创建 iframe 通用组件
IframeTemplate.vue
- 页面布局
<template><div class="iframe-container"></div></template><style scoped>.iframe-container {width: 50%;height: calc(100vh - 124px);}</style>```
iframe
标签创建/**iframe 标签创建 */function createIframe() {try {const { meta: { isIframe }, path, query } = routeif (!isIframe) return;// 地址拼接、带参query等const baseUrl = getBaseUrl() + path + (isIframe ? ".html" : "")let commonIframe = $("#common-iframe")if (commonIframe.length) {commonIframe.attr("src", baseUrl)} else {commonIframe = $('<iframe class="iframe-content" id="common-iframe" width="100%" height="100%" style="overflow:hidden;border:0 none; outline:0"></iframe>')$(".iframe-container").prepend(commonIframe)commonIframe.ready(() => {commonIframe.attr("src", baseUrl)})}} catch (err) {console.log(err)}}/** 根据环境区分iframe页面地址前缀 * server & base 可以根据环境 配置不同的值* 1.webpack添加区分环境的配置* 2.在对应的 .env文件中配置变量*/function getBaseUrl() {const { VUE_WEB_IFRAME_SERVER: server, VUE_WEB_BASEURL: base } = process.env/** 示例: 使用apache代理静态页面(http://localhost:8080/iframe-pages/update.html)* 此处的server=http://localhost:8080,base="",route="/iframe-pages/update"*/return server + base}```
- 监听路由,实现
iframe
地址更新,访问不同页面/* 监听路由变更 - iframe 页面地址更新 */watch(route, () => {createIframe()});onMounted(() => {createIframe()});
添加页面及路由
- 添加路由
// router/index.js// iframe页面独立访问地址: http://localhost:8080/iframe-pages/update.html/** 添加iframe 页面路由 */const iframePages = [{path: '/iframe-pages/base',name: "base"},{path: '/iframe-pages/includes',name: "includes"},{path: '/iframe-pages/update',name: "update"}]let iframeRoute = []iframePages.map(item => {const { path, name } = itemiframeRoute.push({path,name,meta: { isIframe: true },component: () => import('../views/IframePage.vue')})})const router = createRouter({// 其他...routes: [// 其他......iframeRoute]})```
- iframe 通用页面
<!-- IframePage.vue --><template><IframeTemplate></IframeTemplate></template><script setup>import IframeTemplate from "@components/IframeTemplate.vue";</script><style scoped lang="scss"></style>```
- iframe 页面快捷菜单
<!-- App.vue --> <RouterLink to="/iframe-pages/base">Base</RouterLink><RouterLink to="/iframe-pages/includes">Includes</RouterLink><RouterLink to="/iframe-pages/update">Update</RouterLink>```
此时页面就可以根据路由访问嵌套的页面了.
进阶:vue 与 iframe 的双向通讯
实现vue 与 iframe 的双向通讯
代码下载
查看代码地址