keep-alive 是vue内置组件 缓存组件内部状态 避免重新渲染

<keep-alive > 是vue内置的一个组件,可用于缓存动态组件 ,使包裹的动态组件在切换时 保存状态,避免重新渲染

可以缓存组件,也可以缓存路由

复制代码
    <template>
       <div>

        <button @click="switchPage">切换页面</button>

        <keep-alive >

          <component :is="curentComponent"></component>

        </keep-alive>

      </div>
    </template>

<script>

import ComponentA from '@/components/ComponentA.vue'

import ComponentB from '@/components/ComponentB.vue'

import ComponentC from '@/components/ComponentC.vue'

export default {

  components: {

    ComponentA,

    ComponentB,

    ComponentC

  },

  data () {

    return {

      user: {},

      curentComponent: 'ComponentA'

    }

  },

 methods: {

    switchPage () {

      this.curentComponent = this.curentComponent === 'ComponentA' ? 'ComponentB' : 'ComponentA'

    },

}

}

</script>

keep-alive 缓存的组件会有两个钩子函数:activated 和 deactivated

第一次进入被缓存的组件A 会触发beforeCreate ==>created ==>beforeMount ==>mounted ==>activated

离开被缓存的A组件 进入被缓存的B组件,会触发A组件的 deactivated ,则第一次进入被缓存的B组件 会触发beforeCreate ==>created ==>beforeMount ==>A组件的deactivated ==>mounted ==>activated

第二次再进这个被缓存的组件A 只触发activated ,不会再触发beforeCreate, created , beforeMount, mounted

keep-alive 可配置 include 属性,需要保证组件的名称(name)与 include 的值相同的才会被缓存

<div>

<button @click="switchPage">切换页面</button>

<keep-alive include="ComponentBpage,ComponentCpage">

<component :is="curentComponent"></component>

</keep-alive>

</div>

exclude 排除 指定哪些组件不被缓存,优先级大于 include,同include ,需要保证组件的名称(name)与 exclude 的值相同

<div>

<button @click="switchPage">切换页面</button>

<!-- <keep-alive include="ComponentBpage,ComponentCpage"> -->

<keep-alive exclude="ComponentBpage">

<component :is="curentComponent"></component>

</keep-alive>

</div>

被缓存后的组件 数据获取方式:

activated 中获取,因为进入缓存组件 不会触发 created 和 mounted钩子函数,会触发activated钩子函数

在 beforeRouteEnter 钩子函数中,在路由进入之前先获取数据。每次组件渲染或者每次进入路由的时候,都会执行 beforeRouteEnter

缓存路由:

include 也可以使用数组,使用 v-bind

相关推荐
晓天衡宇•评测社区3 小时前
Seedance 2.5 登顶图生视频榜单,Wan 3.0 在游戏与教育场景进入前列
前端·javascript·网络
码海无涯回头无岸3 小时前
Ai agent - LLM是一个函数
前端
Profile排查笔记3 小时前
指纹浏览器推荐:用一套验收清单筛选 Profile、代理与自动化能力
前端·人工智能·后端·自动化
卡皮巴拉c993 小时前
基于pnpm搭建monorepo项目
前端·javascript
hweiyu003 小时前
Redis命令:TTL
redis·缓存
torpidcat3 小时前
ruoyi-vue-pro 若依芋道 java springboot +mybatis 生日查询相关
java·vue.js·spring boot
yume_sibai3 小时前
CSS2 核心知识点完全总结(选择器 + 三大特性 + 常用属性)
前端·css
掘金者阿豪4 小时前
不装 SSH 客户端也能连服务器:用 WebSSH 把终端搬进浏览器
前端
Bug修理工Bubble4 小时前
Optional:为什么一个 String? 能让代码少掉很多崩溃?
前端
巴勒个啦4 小时前
2026 年 CSS 选型真相:我用 Tailwind v4 + 原生新特性重构了一个组件库
前端·angular.js