vue-element-admin项目中tagView嵌入iframe不刷新重载

发布时间 2023-08-22 11:56:37作者: 浪里小韭菜

vue-element-admin项目中tagView嵌入iframe不刷新重载

最近使用vue-element-admin来开发项目,因为以前老项目太大,暂不重构,如要通过iframe嵌套在新项目中,通过router来重写url加载,但是业务需要切换菜单或者tagView不能刷新重载iframe页面,因此需要改造

一、vue-element-admin是通过keep-alive来缓存router-view组件内容,但是其router-view中的iframe是重新通过src加载,相当于iframe重载

- 解决方案:
 - iframe组件不走keep-alive和router-view,而是一直处在body中
 ```
 // AppMain.vue
 <transition name="fade-transform" mode="out-in">
  <!-- iframe不走重新加载,而是隐藏,保证重载, isIframePage 通过router.meta.type字段来判断-->
  <template v-if="isIframePage">
    <iframe-contain />
  </template>
  
  <template v-else>
    <keep-alive :include="cachedViews" :exclude="notCachedViews">
      <router-view :key="key" />
    </keep-alive>
  </template>

</transition>
 ```

二、监听$route,收集iframe消息,存入Array中,通过当前路由来展示和隐藏

- 解决方案:
```
// iframeContain.vue
  <div class="iframe-contain">
	<el-card class="iframe-contant el-card-8">
	  <iframe 
		v-show="curIframeName === item.name" 
		v-for="item in iframeUrlArr" 
		:key="item.name " 
		id="frameBox" 
		:src="item.url" 
		class="frame-box" />
	</el-card>
  </div>
  
  // script
  import { uniqBy } from 'lodash';
  data() {
	  curIframeName: '', // 当前iframe名称,唯一值
	  iframeUrlArr: [], // 收集所有打开的iframe
  },
  watch: {
	$route: {
	  handler: function(route) {
		console.log('路由', route, this)
		this.curIframeName = route.name;
		this.iframeUrlArr.push({
		  name: route.name,
		  url: window.location.origin + (route.meta.specialUrl || route.path), // 根据自己项目来写
		})

		// 去重,可自己写方法Object.keys, includes, push
		this.iframeUrlArr = uniqBy(this.iframeUrlArr, 'name')
	  },
	  immediate: true
	}
  },
```