Vue中对iframe实现keep alive无刷新的方法

2020-06-14 06:01:57易采站长站整理

this.isOpenIframePage();
},
data() {
return {
componentsArr: [] // 含有iframe的页面
}
},
watch: {
$route() {
// 判断当前路由是否iframe页
this.isOpenIframePage();
}
},
computed: {
// 实现懒加载,只渲染已经打开过(hasOpen:true)的iframe页
hasOpenComponentsArr() {
return this.componentsArr.filter(item => item.hasOpen);
}
},
methods: {
// 根据当前路由设置hasOpen
isOpenIframePage() {
const target = this.componentsArr.find(item => {
return item.path === this.$route.path
});
if (target && !target.hasOpen) {
target.hasOpen = true;
}
},
// 遍历路由的所有页面,把含有iframeComponent标识的收集起来
getComponentsArr() {
const router = this.$router;
const routes = router.options.routes;
const iframeArr = routes.filter(item => item.iframeComponent);

return iframeArr.map((item) => {
const name = item.name || item.path.replace('/', '');
return {
name: name,
path: item.path,
hasOpen: false, // 是否打开过,默认false
component: item.iframeComponent // 组件文件的引用
};
});
}
}
}
</script>

该组件主要做的是根据main.ja里的routes生成一个只含有iframe页的数组对象。
watch上监听$route,判断当前页面在iframe页列表里的话就设置hasOpen属性为true,渲染该组件
用v-show=”$route.path === item.path”切换iframe页的显示与隐藏。

逻辑并不复杂,这里就不多赘述。

结语

大家如果有更好的实现方法,或者我上面还有什么需要更正的错误,欢迎交流。 上面demo的代码放在了个人github上 https://github.com/jmx164491960/vue-iframe-demo