vue中Keep-alive组件生命周期的使用

328 阅读1分钟

国内目前用vue做开发的比较多。Vue凡物都是组件,其中有个keep-alive的很有意思:找到官网,有如下说明: When wrapped around a dynamic component, <keep-alive> caches the inactive component instances without destroying them. Similar to <transition><keep-alive> is an abstract component: it doesn’t render a DOM element itself, and doesn’t show up in the component parent chain.

When a component is toggled inside <keep-alive>, its activated and deactivated lifecycle hooks will be invoked accordingly.

In 2.2.0+ and above, activated and deactivated will fire for all nested components inside a <keep-alive> tree.

keep-alive的用法: 这样componnet在来回复切换一不同的组件的时候,会缓存起来,不会重新创建。keep-alive的组件会有生命周期函数activated 和 deactivated vue 2.2+后,keep-alive下面的所有子组件都会activated 和 deactivated生命周期。

一个非常有用的例子:项目有个需求,在页面窗口大小变化时,要求内部的echart图也随之变化,所以会用到window.removeEventListener('resize',this.resize) window.addEventListener('resize',this.resize) 这样的事件绑定和移除方法。如果不做页面退出时的处理,别的页面的resize事件会影响本页面。为了避免本页面被其它页面影响,就要用到deactivated生命周期,在deactivated里window.removeEventListener('resize',this.resize)一下事件。然后在activated生命周期里面加上window.removeEventListener('resize',this.resize) window.addEventListener('resize',this.resize)就可以在window变化时调用自己的resize业务。