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

相关推荐
Data_Journal42 分钟前
什么是 CAPTCHA,它是如何工作的?
java·大数据·服务器·前端·数据库
计算机魔术师1 小时前
我看了这个更新,把原来的检索方案推翻了
前端
霸道流氓气质1 小时前
Redis Pub/Sub — 概念、原理、场景与代码示例
数据库·redis·缓存
zhanghaha13141 小时前
HTML系列教程:3_HTML 基础标签 — 标题、段落、超链接、图像
前端·html
李高钢1 小时前
C# WPF Prism 进阶(二):区域(Region)与模块化(Module)
java·前端·数据库
xyphf_和派孔明2 小时前
Vite 与 Webpack 对比及常见面试题
前端·webpack·vite
明月_清风2 小时前
Pi Agent 深度解析:开源极简终端 AI 编码代理的终极指南
前端·后端·ai编程
fatcoder2 小时前
玩转Nginx 03 — location 匹配规则:让不同的路径各回各家
前端·后端·nginx
HjhIron2 小时前
前端面试高频考点 —— TS 高级类型 & CSS 三列布局
前端
李剑一2 小时前
《牛来》火了?我用ThreeJs实现了一个简易版的,代码全送给你,文章最后附演示效果
前端