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

前言

最近一个需求,需要在 Vue 项目中加入 含有iframe 的页面,同时在路由切换的过程中,要求iframe的内容 不会被刷新 。一开始使用了Vue自带的keep- alive发现没有用,于是自己研究了一下解决方案。。。。。。

Vue的keep-alive原理
要实现对保持iframe页的状态。我们先搞清楚为什么Vue的keep-alive不能凑效。keep-alive原理是把组件里的节点信息保留在了 VNode (在内存里),在需要渲染时候从Vnode渲染到真实DOM上。iframe页里的内容并不属于节点的信息,所以使用keep-alive依然会重新渲染iframe内的内容。 另外 ,我也尝试有过想法:如果把整个iframe节点保存起来,然后需要切换时把它渲染到目标节点上,能否实现iframe页不被刷新呢?————也是不可行的,iframe每一次渲染就相当于打开一个新的网页窗口,即使把节点保存下来,在渲染时iframe页还是刷新的。

实现的思路
既然保持iframe页里的状态很难实现,在这个时候我想到了一个别的方法。能否在Vue的route-view节点上动点手脚?使得在切换 非iframe页 的时候使用Vue的路由,当切换 iframe页 时则使用 v-show 切换显示与隐藏,使得iframe节点 一直不被删除 ,这样就能保持iframe的状态了。

我们简陋的实现一下以上的效果,上代码:

入口main.js:

import Vue from 'vue/dist/vue.js'
import App from './App.vue'
import VueRouter from 'vue-router';
 
const Index = {
    template: '<div>Index</div>' }
const routes = [
 // 含有iframe的两个页面
 {
   
 path: '/f1',
 name: 'f1'
 },
 // 含有iframe的两个页面
 {
   
 path: '/f2',
 name: 'f2'
 },
 {
   
 path: '/index',
 component: Index
 }
]
 
const router = new VueRouter({
   
 routes
});
 
Vue.use(VueRouter);
new Vue({
   
 render: h => h(App),
 router
}).$mount('#app')

根组件:

<template>
 <div id="app">
 <div class="nav">
  <router-link class="router" to="/f1">Go to F1</router-link>
  <router-link class="router" to="/f2">Go to F2</router-link>
  <router-link class="router" to="/index
  • 7
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 13
    评论
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值