今天和大家聊聊vue中的keep-alive
keep-alive是什么?
Vue.js 中的一个内置组件,用于缓存动态组件的状态
效果展示

代码示例
接下来我们做一个demo,目录结构为
js
src/
├── components/
│ ├── Home.vue
│ └── About.vue
├── App.vue
└── router/
└── index.js
- Home
js
<template>
<div>
<h1>Home</h1>
<p>当前时间:{{ currentTime }}</p>
<button @click="updateTime">更新时间</button>
</div>
</template>
<script setup>
import { ref, onActivated, onDeactivated } from "vue";
const currentTime = ref(new Date().toLocaleTimeString());
const updateTime = () => {
currentTime.value = new Date().toLocaleTimeString();
};
onActivated(() => {
console.log("Home组件激活");
});
onDeactivated(() => {
console.log("Home组件失活");
});
</script>
- About
js
<template>
<div>
<h1>About</h1>
<p>这里是关于页面</p>
</div>
</template>
<script setup>
import { onActivated, onDeactivated } from "vue";
onActivated(() => {
console.log("About组件激活");
});
onDeactivated(() => {
console.log("About组件失活");
});
</script>
- router
js
import { createRouter, createWebHistory } from "vue-router";
import Home from "../components/Home.vue";
import About from "../components/About.vue";
const routes = [
{ path: "/", name: "Home", component: Home },
{ path: "/about", name: "About", component: About },
];
const router = createRouter({
history: createWebHistory(),
routes,
});
export default router;
- App
js
<template>
<div id="app">
<nav>
<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
</nav>
<router-view v-slot="{ Component }">
<keep-alive>
<component :is="Component" />
</keep-alive>
</router-view>
</div>
</template>
<script>
export default {};
</script>
<style>
nav {
margin-bottom: 20px;
}
</style>
运行结果
首先我们进入到Home页面,打印结果为,并且我们切换的时候home页面显示的时间为12:47:44

接下来我们跳转到About页面就会发现,home组件失活,about组件激活

继续回到home组件,我们能够看到,在我们切换home页码的时间是什么时候,回来的时间还是一样的,可见,数据被缓存下来了

总结
使用 <keep-alive>
组件可以有效地缓存 Vue 组件,从而提高应用性能和用户体验。当一个组件被缓存时,它的状态和数据会被保留,用户在切换回该组件时能够看到之前的状态。
如果需要在组件消失时执行特定的操作(例如,清理资源、保存状态或停止定时器),可以将相关的方法定义在 onDeactivated
钩子中。这样,当组件被去激活时,这些方法会自动执行,确保组件在被移除前能够完成必要的清理工作。
这种方式不仅提高了代码的可读性,还能有效管理组件的生命周期,避免内存泄漏等问题。通过合理使用 onActivated
和 onDeactivated
钩子,可以更好地控制组件的行为和状态。