什么是keep-alive
keep-alive是Vue提供的一个抽象组件,用来对组件进行缓存,从而节省性能,由于是一个抽象组件,所以在页面渲染完毕后不会被渲染成一个DOM元素。
简单的来说,在点击切换不同组件的时候,为了降低消耗,就将包裹的组件缓存起来。
keep-alive组件上的三个属性
- include:名称匹配的组件会被缓存
- exclude:任何名称匹配的组件都不会被缓存
- max: 最多可以缓存多少组件实例。一旦这个数字达到了,在新实例被创建之前,已缓存组件中最久没有被访问的实例会被销毁掉。
两个回调函数
- activated:在缓存的组件中,当切换显示时触发
- deactivated:在缓存的组件中,当显示切换隐藏时触发
注意:是在缓存的组件中的,如何组件没有缓存,即使是被keep-alive包裹着也不会触发
//html
<!-- 需要缓存的组件 -->
<keep-alive include="acomp">
<!-- 动态组件 v-bind:is为显示的组件名 -->
<component :is="view"></component>
</keep-alive>
<button
v-for="(item, index) in btnList"
:key="index"
@click="select(item.name)"
>切换{{item.name}}</button>
//js
data() {
return {
view: "bcomp",
btnList: [
{
id: 1,
name: "a"
},
{
id: 2,
name: "b"
},
{
id: 3,
name: "c"
}
]
};
},
components: {
acomp: Acomp,
bcomp: Bcomp
},
methods: {
select(e) {
this.view = e + "comp";
}
}
- A组件中
activated() {
console.log("显示A");
},
deactivated(){
console.log("隐藏A");
}