iframe配合Vue的keep-alive实现缓存

# 第一步:keep-alive

<template>
  <!-- 缓存 Header,Footer -->
  <keep-alive :include="['Test1', 'Test2']">
    <!-- 动态组件 -->
    <component :is="currentView"></component>
  </keep-alive>
</template>
1
2
3
4
5
6
7

# 第二步:封装 iframe 组件

<template>
  <teleport to="body">
      <iframe 
        class="iframe_style"
        v-show="visible"
        :src="url" 
        frameborder="no" 
        scrolling="auto" />
  </teleport>
    

  
</template>

<script setup>
import { computed, onBeforeUnmount, onDeactivated, onUnmounted } from 'vue'

const props = defineProps({
  src: {
    type: String,
    required: true
  },
  top: {
    type: String,
    default: '100px',
    required: true,
  },
  left: {
    type: String,
    default: '100px',
    required: true,
  },
})

const computedTop = computed(() => props.top) // 距离浏览器顶部距离
const computedLeft = computed(() => props.left) // 距离浏览器左边距离
const computedWidth = computed(() => `calc(100vw - ${props.left})`) // 距离浏览器左边距离
const computedHeight = computed(() => `calc(100vh - ${props.top})`) // 距离浏览器左边距离


const url = computed(() => props.src)

const visible = ref(true)
onActivated(() => {
    visible.value = true // 进入显示
    // console.log('iframe',visible.value)
})
onDeactivated(() => {
    visible.value = false // 离开隐藏
    // console.log('iframe',visible.value)
})
</script>

<style scoped>
.iframe_style {
  position: fixed;
  /* top: 90px; */
  /* left: 205px; */
  top: v-bind(computedTop);
  left: v-bind(computedLeft);
  width: v-bind(computedWidth);
  height: v-bind(computedHeight);
}
</style>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65

# 第三步:在被缓存的路由组件中使用

  • 注意:script里面一定要有代码,iframe 才能被缓存
<template>
    <div>
        <iFrame :src="'https://www.baidu.com/'" :top="'90px'" :left="'205px'" />
    </div>
</template>

<script name="Test1" setup>
// onActivated(()=>{}) 这里面必须要有代码,写个注释啥的都行
</script>

1
2
3
4
5
6
7
8
9
10
最近更新时间: 2025/09/28 09:58:00
最近更新
01
2025/09/15 00:00:00
02
2025/08/20 00:00:00
03
2025/07/18 00:00:00