vue keep-alive组件使用

keep-alive是Vue.js的一个内置组件。<keep-alive> 包裹动态组件时,会缓存不活动的组件实例,而不是销毁它们。它自身不会渲染一个 DOM 元素,也不会出现在父组件链中。 当组件在 <keep-alive> 内被切换,它的 activated 和 deactivated 这两个生命周期钩子函数将会被对应执行。它提供了include与exclude两个属性,允许组件有条件地进行缓存。

举个栗子

 
  1. <keep-alive>

  2. <router-view v-if="$route.meta.keepAlive"></router-view>

  3. </keep-alive>

  4. <router-view v-if="!$route.meta.keepAlive"></router-view>

  5. 复制代码


切换按钮

在点击button时候,两个input会发生切换,但是这时候这两个输入框的状态会被缓存起来,input标签中的内容不会因为组件的切换而消失。

 
  1. * include - 字符串或正则表达式。只有匹配的组件会被缓存。

  2. * exclude - 字符串或正则表达式。任何匹配的组件都不会被缓存。

  3. 复制代码

 
  1. <keep-alive include="a">

  2. <component></component>

  3. </keep-alive>

  4. 复制代码

只缓存组件别民name为a的组件

 
  1. <keep-alive exclude="a">

  2. <component></component>

  3. </keep-alive>

  4. 复制代码

除了name为a的组件,其他都缓存下来

生命周期钩子

生命钩子keep-alive提供了两个生命钩子,分别是activated与deactivated。

因为keep-alive会将组件保存在内存中,并不会销毁以及重新创建,所以不会重新调用组件的created等方法,需要用activated与deactivated这两个生命钩子来得知当前组件是否处于活动状态。

深入keep-alive组件实现

查看vue--keep-alive组件源代码可以得到以下信息

created钩子会创建一个cache对象,用来作为缓存容器,保存vnode节点。

 
  1.  
  2. props: {

  3. include: patternTypes,

  4. exclude: patternTypes,

  5. max: [String, Number]

  6. },

  7.  
  8. created () {

  9. // 创建缓存对象

  10. this.cache = Object.create(null)

  11. // 创建一个key别名数组(组件name)

  12. this.keys = []

  13. },

  14. 复制代码

destroyed钩子则在组件被销毁的时候清除cache缓存中的所有组件实例。

 
  1. destroyed () {

  2. /* 遍历销毁所有缓存的组件实例*/

  3. for (const key in this.cache) {

  4. pruneCacheEntry(this.cache, key, this.keys)

  5. }

  6. },

  7. 复制代码

:::demo

 
  1. render () {

  2. /* 获取插槽 */

  3. const slot = this.$slots.default

  4. /* 根据插槽获取第一个组件组件 */

  5. const vnode: VNode = getFirstComponentChild(slot)

  6. const componentOptions: ?VNodeComponentOptions = vnode && vnode.componentOptions

  7. if (componentOptions) {

  8. // 获取组件的名称(是否设置了组件名称name,没有则返回组件标签名称)

  9. const name: ?string = getComponentName(componentOptions)

  10. // 解构对象赋值常量

  11. const { include, exclude } = this

  12. if ( /* name不在inlcude中或者在exlude中则直接返回vnode */

  13. // not included

  14. (include && (!name || !matches(include, name))) ||

  15. // excluded

  16. (exclude && name && matches(exclude, name))

  17. ) {

  18. return vnode

  19. }

  20.  
  21. const { cache, keys } = this

  22. const key: ?string = vnode.key == null

  23. // same constructor may get registered as different local components

  24. // so cid alone is not enough (#3269)

  25. ? componentOptions.Ctor.cid + (componentOptions.tag ? `::${componentOptions.tag}` : '')

  26. : vnode.key

  27. if (cache[key]) { // 判断当前是否有缓存,有则取缓存的实例,无则进行缓存

  28. vnode.componentInstance = cache[key].componentInstance

  29. // make current key freshest

  30. remove(keys, key)

  31. keys.push(key)

  32. } else {

  33. cache[key] = vnode

  34. keys.push(key)

  35. // 判断是否设置了最大缓存实例数量,超过则删除最老的数据,

  36. if (this.max && keys.length > parseInt(this.max)) {

  37. pruneCacheEntry(cache, keys[0], keys, this._vnode)

  38. }

  39. }

  40. // 给vnode打上缓存标记

  41. vnode.data.keepAlive = true

  42. }

  43. return vnode || (slot && slot[0])

  44. }

  45.  
  46. // 销毁实例

  47. function pruneCacheEntry (

  48. cache: VNodeCache,

  49. key: string,

  50. keys: Array<string>,

  51. current?: VNode

  52. ) {

  53. const cached = cache[key]

  54. if (cached && (!current || cached.tag !== current.tag)) {

  55. cached.componentInstance.$destroy()

  56. }

  57. cache[key] = null

  58. remove(keys, key)

  59. }

  60.  
  61.  
  62. // 缓存

  63. function pruneCache (keepAliveInstance: any, filter: Function) {

  64. const { cache, keys, _vnode } = keepAliveInstance

  65. for (const key in cache) {

  66. const cachedNode: ?VNode = cache[key]

  67. if (cachedNode) {

  68. const name: ?string = getComponentName(cachedNode.componentOptions)

  69. // 组件name 不符合filler条件, 销毁实例,移除cahe

  70. if (name && !filter(name)) {

  71. pruneCacheEntry(cache, key, keys, _vnode)

  72. }

  73. }

  74. }

  75. }

  76.  
  77. // 筛选过滤函数

  78. function matches (pattern: string | RegExp | Array<string>, name: string): boolean {

  79. if (Array.isArray(pattern)) {

  80. return pattern.indexOf(name) > -1

  81. } else if (typeof pattern === 'string') {

  82. return pattern.split(',').indexOf(name) > -1

  83. } else if (isRegExp(pattern)) {

  84. return pattern.test(name)

  85. }

  86. /* istanbul ignore next */

  87. return false

  88. }

  89.  
  90.  
  91. // 检测 include 和 exclude 数据的变化,实时写入读取缓存或者删除

  92. mounted () {

  93. this.$watch('include', val => {

  94. pruneCache(this, name => matches(val, name))

  95. })

  96. this.$watch('exclude', val => {

  97. pruneCache(this, name => !matches(val, name))

  98. })

  99. },

  100.  
  101. 复制代码

:::

通过查看Vue源码可以看出,keep-alive默认传递3个属性,include 、exclude、max, max 最大可缓存的长度

结合源码我们可以实现一个可配置缓存的router-view

 
  1. <!--exclude - 字符串或正则表达式。任何匹配的组件都不会被缓存。-->

  2. <!--TODO 匹配首先检查组件自身的 name 选项,如果 name 选项不可用,则匹配它的局部注册名称-->

  3. <keep-alive :exclude="keepAliveConf.value">

  4. <router-view class="child-view" :key="$route.fullPath"></router-view>

  5. </keep-alive>

  6. <!-- 或者 -->

  7. <keep-alive :include="keepAliveConf.value">

  8. <router-view class="child-view" :key="$route.fullPath"></router-view>

  9. </keep-alive>

  10. <!-- 具体使用 include 还是exclude 根据项目是否需要缓存的页面数量多少来决定-->

  11. 复制代码

创建一个keepAliveConf.js 放置需要匹配的组件名

 
  1. // 路由组件命名集合

  2. var arr = ['component1', 'component2'];

  3. export default {value: routeList.join()};

  4. 复制代码

配置重置缓存的全局方法

 
  1. import keepAliveConf from 'keepAliveConf.js'

  2. Vue.mixin({

  3. methods: {

  4. // 传入需要重置的组件名字

  5. resetKeepAive(name) {

  6. const conf = keepAliveConf.value;

  7. let arr = keepAliveConf.value.split(',');

  8. if (name && typeof name === 'string') {

  9. let i = arr.indexOf(name);

  10. if (i > -1) {

  11. arr.splice(i, 1);

  12. keepAliveConf.value = arr.join();

  13. setTimeout(() => {

  14. keepAliveConf.value = conf

  15. }, 500);

  16. }

  17. }

  18. },

  19. }

  20. })

  21. 复制代码

在合适的时机调用调用this.resetKeepAive(name),触发keep-alive销毁组件实例;

Vue.js内部将DOM节点抽象成了一个个的VNode节点,keep-alive组件的缓存也是基于VNode节点的而不是直接存储DOM结构。它将满足条件的组件在cache对象中缓存起来,在需要重新渲染的时候再将vnode节点从cache对象中取出并渲染。


作者:walker-design
链接:https://juejin.im/post/5b4320f9f265da0f7f4488f6
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

转载于:https://blog.csdn.net/sinat_17775997/article/details/80993644

猜你喜欢

转载自blog.csdn.net/a460550542/article/details/84854453