聊聊vue中的keep-alive

今天和大家聊聊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 钩子中。这样,当组件被去激活时,这些方法会自动执行,确保组件在被移除前能够完成必要的清理工作。

这种方式不仅提高了代码的可读性,还能有效管理组件的生命周期,避免内存泄漏等问题。通过合理使用 onActivatedonDeactivated 钩子,可以更好地控制组件的行为和状态。

相关推荐
崔庆才丨静觅12 小时前
hCaptcha 验证码图像识别 API 对接教程
前端
passerby606113 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了13 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅13 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅13 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅14 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment14 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅14 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊14 小时前
jwt介绍
前端