# KeepAlive

# 缓存状态

  1. 保存指定组件的状态,即使切换组件也不会初始化组件
<template>
  <keep-alive>
    <component :is='component'>
  </keep-alive>
</template>

<script>
export default {
  component: {
    component1,
    component2
  },
  data() {
    return {
      component: 'component1' //假设有个组件叫header
    }
  }
}
</script>

2.保存指定路由状态

  • 使用includs
<template>
  <!-- 组件里的里自定义的 name='a' 或者路由里的n ame='a' -->
  <keep-alive includs='a,b'></keep-alive>
  <keep-alive :includs="['a', 'b']"></keep-alive>
</template>
  • 使用excluds
<template>
  <!-- 不保存a,b组件状态 -->
  <keep-alive excluds='a,b'></keep-alive>
  <keep-alive :excluds="['a', 'b']"></keep-alive>
</template>

# keepalive 生命周期

  • 初始进入一样会触发createdmounted,但被缓存之后就只会触发以下两个生命周期。
activated() {
  // 进入被缓存的组件或者路由
},
deactivated() {
  // 离开被缓存的组件或者路由
}

# FAQ

复用组件无法清除

如果碰到使用了url/:id这种页面需要缓存,需要指定唯一key但是可能会导致关闭页面也无法销毁对应的实例, 可以使用以下方式去做对应处理。

清除 keepalive 缓存
  • 某些特殊情况可能会导致缓存清除不掉 可以使用$destory()
activated() {
  this.$once('hook:deactivated', () => {
    this.$destory()
  })
}
使用 key 关键字来为路由页面指定唯一值
<template>
  <keep-alive>
    <router-view :key="$route.path"/>
  </keep-alive>
</template>