前置知识: Vue 3

KeepAlive缓存与生命周期

00:00
1 min Advanced 2026/6/14

Vue 3 KeepAlive组件缓存机制与activated/deactivated生命周期。

1. KeepAlive 基础

1.1 基本用法

<RouterView v-slot="{ Component }">
  <KeepAlive>
    <component :is="Component" />
  </KeepAlive>
</RouterView>

1.2 缓存策略

<!-- 缓存指定组件 -->
<KeepAlive include="UserList,Settings">
  <component :is="current" />
</KeepAlive>

<!-- 排除指定组件 -->
<KeepAlive exclude="Login">
  <component :is="current" />
</KeepAlive>

<!-- 最大缓存数 -->
<KeepAlive :max="10">
  <component :is="current" />
</KeepAlive>

2. 生命周期钩子

import { onActivated, onDeactivated } from 'vue';

export default {
  setup() {
    onActivated(() => {
      console.log('组件被激活');
    });

    onDeactivated(() => {
      console.log('组件被停用');
    });
  },
};
钩子触发时机
onActivated组件缓存激活时
onDeactivated组件缓存停用时

3. 缓存刷新

// 需要刷新缓存时,移除 include 中的组件名
const cachedViews = ref(['UserList', 'Settings']);

function refreshCache(name) {
  cachedViews.value = cachedViews.value.filter((v) => v !== name);
  nextTick(() => {
    cachedViews.value.push(name);
  });
}

知识检测

学习进度

-- 已学文档
--% 知识覆盖率

学习推荐

专注模式