vue keep-alive组件的使用以及原理介绍


当前第2页 返回上一页

1

2

3

4

5

6

7

8

9

10

11

12

/* 检测name是否匹配 */

function matches (pattern: string | RegExp, name: string): boolean {

  if (typeof pattern === 'string') {

    /* 字符串情况,如a,b,c */

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

  } else if (isRegExp(pattern)) {

    /* 正则 */

    return pattern.test(name)

  }

  /* istanbul ignore next */

  return false

}

检测include与exclude属性匹配的函数很简单,include与exclude属性支持字符串如"a,b,c"这样组件名以逗号隔开的情况以及正则表达式。matches通过这两种方式分别检测是否匹配当前组件。

1

2

3

4

5

if (this.cache[key]) {

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

} else {

    this.cache[key] = vnode

}

接下来的事情很简单,根据key在this.cache中查找,如果存在则说明之前已经缓存过了,直接将缓存的vnode的componentInstance(组件实例)覆盖到目前的vnode上面。否则将vnode存储在cache中。
最后返回vnode(有缓存时该vnode的componentInstance已经被替换成缓存中的了)。
用watch来监听pruneCache与pruneCache这两个属性的改变,在改变的时候修改cache缓存中的缓存数据。

1

2

3

4

5

6

7

8

9

watch: {

    /* 监视include以及exclude,在被修改的时候对cache进行修正 */

    include (val: string | RegExp) {

        pruneCache(this.cache, this._vnode, name => matches(val, name))

    },

    exclude (val: string | RegExp) {

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

    }

},

来看一下pruneCache的实现。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

/* 修正cache */

function pruneCache (cache: VNodeCache, current: VNode, filter: Function) {

  for (const key in cache) {

    /* 取出cache中的vnode */

    const cachedNode: ?VNode = cache[key]

    if (cachedNode) {

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

      /* name不符合filter条件的,同时不是目前渲染的vnode时,销毁vnode对应的组件实例(Vue实例),并从cache中移除 */

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

        if (cachedNode !== current) {

          pruneCacheEntry(cachedNode)

        }

        cache[key] = null

      }

    }

  }

}

 

/* 销毁vnode对应的组件实例(Vue实例) */

function pruneCacheEntry (vnode: ?VNode) {

  if (vnode) {

    vnode.componentInstance.$destroy()

  }

}

遍历cache中的所有项,如果不符合filter指定的规则的话,则会执行pruneCacheEntry。pruneCacheEntry则会调用组件实例的$destroy方法来将组件销毁。

本篇文章到这里就已经全部结束了,更多其他精彩内容可以关注PHP中文网的JavaScript视频教程栏目!

以上就是vue keep-alive组件的使用以及原理介绍的详细内容,更多文章请关注木庄网络博客

返回前面的内容

相关阅读 >>

详解javascript扩展运算符的10种用法(总结)

7个javascript中关于闭包的面试题,你能回答上来吗?

javascript中如何声明常量

array中 foreach() 和 map() 的区别

javascript如何设置width

如何打开javascript

javascript如何关闭网页

javascript数组怎么求和

javascript中怎么使用item方法

使用gpu.js提高javascript应用性能的小技巧

更多相关阅读请进入《javascript》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...