目录
keep-alive
使用 keep-alive
的示例代码:
<template>
<div>
<button @click="toggleComponent">切换组件</button>
<keep-alive>
<component :is="currentComponent"></component>
</keep-alive>
</div>
</template>
<script>
export default {
data() {
return {
currentComponent: 'ComponentA',
};
},
methods: {
toggleComponent() {
if (this.currentComponent === 'ComponentA') {
this.currentComponent = 'ComponentB';
} else {
this.currentComponent = 'ComponentA';
}
},
},
};
</script>
我们有两个组件 ComponentA
和 ComponentB
,点击按钮可以在两者之间进行切换。这两个组件被包裹在 keep-alive
组件中,所以切换时不会销毁和重新创建它们的实例。
如果你想手动清除 keep-alive
中的组件缓存,可以使用 include
和 exclude
属性。这两个属性接受一个字符串或正则表达式的数组,用于匹配需要缓存或排除的组件。
手动清除组件缓存的示例代码:
<template>
<div>
<button @click="clearCache">清除缓存</button>
<keep-alive :include="includedComponents" :exclude="excludedComponents">
<component :is="currentComponent"></component>
</keep-alive>
</div>
</template>
<script>
export default {
data() {
return {
currentComponent: 'ComponentA',
includedComponents: ['ComponentA'], // 需要缓存的组件列表
excludedComponents: [], // 不需要缓存的组件列表
};
},
methods: {
clearCache() {
this.$refs.keepAlive.cache = {};
},
},
};
</script>
添加一个按钮来触发清除缓存。includedComponents
数组用于指定需要缓存的组件,而 excludedComponents
数组用于指定不需要缓存的组件。通过修改这两个数组,你可以控制哪些组件应该被缓存或排除。
点击清除缓存按钮时,我们调用 this.$refs.keepAlive.cache = {};
来直接清空 keep-alive
组件的缓存。
keep-alive
组件有以下几个优点:
keep-alive
的原理: