- keep-alive是Vue的一个内置组件,使页面切换时可以将状态保留在内存中,或防止重复渲染DOM。
- keep-alive组件有三个props
include
(符合要求的缓存)、exclude
(符合要求的不缓存)、max
(最多缓存的数量) - include、exclude可以是以逗号分割的字符串.数组。正则表达式
<!-- 逗号分隔字符串 -->
<template>
<section class="app-main">
<transition name="fade-transform" mode="out-in">
<keep-alive :include="a,b">
<router-view :key="$route.path" />
</keep-alive>
</transition>
</section>
</template>
<!-- 正则表达式 (使用 `v-bind`) -->
<template>
<section class="app-main">
<transition name="fade-transform" mode="out-in">
<keep-alive :include="/a|b/">
<component :is="view"></component>
</keep-alive>
</transition>
</section>
</template>
<!-- 数组 (使用 `v-bind`) -->
<template>
<section class="app-main">
<transition name="fade-transform" mode="out-in">
<keep-alive :include="[a,b]">
<router-view :key="$route.path" />
</keep-alive>
</transition>
</section>
</template>
- 匹配首先检查自身的name选项,其次匹配局部注册的名称(父组件 components 选项的键值)。匿名组件不能被匹配。
- 被keep-alive包裹的页面,会多activated和deactivated两个钩子函数。
- 首次进入组件钩子的执行函数 beforeRouteEnter ——》beforeCreate——》created——》beforeMount——》mounted——》activated ——》… ——》beforeRouteLeave ——》deactivated
- 再次进入组件钩子执行顺序 beforeRouteEnter ——》activated ——》… ——》beforeRouteLeave ——》deactivated
- 缓存后获取数据通过beforeRouteEnter和activated方法
beforeRouteEnter(to, from, next){
next(vm=>{
console.log(vm)
vm.getData()
})
},
methods: {}
activated(){
this.getData()
},