vue3-keep-alive具体使用及白屏问题

2,271 阅读1分钟

文件目录

  • App.vue ----> FatherPage -----> A、B.vue

V%TH(R6UL(DTT7BWGKZSLVC.png

效果

缓存A, 不缓存B

nRqgn6nlYl.gif

代码

  • fahtherPage上的代码
<router-view v-slot="{ Component }">
  <keep-alive :exclude="['B']">
    <component :is="Component"></component>
  </keep-alive>
</router-view>
  • 路由A、B中 路由就是组件, 所以我们用到excludeinclude的时候, 就需要给组件加上name
    vue3中组件加name
<template>
  <div class="">
    A
    <input type="text" />
  </div>
</template>

<script>
export default {
  name: "A"
};
</script>
<script setup>
// to do...
</script>

keep-alive注意点

1、不要在router-view上加keyrouter-view加key的区别
2、如果要缓存,一定要在template上加个根标签,根标签不该是router-view,不然会白屏
3、keep-alive不支持缓存孙子组件
4、一定要给组件加上name

vue3缓存白屏说明

  • 添加缓存的路由

如果template下面直接是router-view,路由跳转会直接白屏,这跟vue3template设计正好相反。。

<template>
  <router-view v-slot="{ Component }" :key="$route.fullPath">
    <keep-alive :include="['flinkWork', 'sparkWork']">
      <component :is="Component"></component>
    </keep-alive>
  </router-view>
</template> 

解决:需要加上根标签,外面加一层div

<template>
  <div class="work-manage">
    <router-view v-slot="{ Component }" >
      <keep-alive :include="['flinkWork', 'sparkWork']">
        <component :is="Component"></component>
      </keep-alive>
    </router-view>
  </div>
</template>