Effective Component Caching with Vue's Keep-Alive
keep-alive is an abstract component that caches inactive component instances. It preserves component state to prevent re-rendering, which optimizes performance when components are frequently toggled.
Core Implementation
Wrap dynamic components with keep-alive to enable instance caching.
<template>
<div id="app">
<nav>
<button @click="activeTab = 'TabOne'">Tab One</button>
<button @click="activeTab = 'TabTwo'">Tab Two</button>
</nav>
<keep-alive>
<component :is="activeTab"></component>
</keep-alive>
</div>
</template>
<script>
export default {
name: 'App',
data() {
return {
activeTab: 'TabOne'
};
},
components: {
TabOne: () => import('./TabOne.vue'),
TabTwo: () => import('./TabTwo.vue')
}
};
</script>
Selective Caching with include and exclude
The include and exclude props control which components are cached. Values can be strings, arrays, or regular expressions.
<!-- Cache only the component named 'UserProfile' -->
<keep-alive include="UserProfile">
<component :is="currentComponent"></component>
</keep-alive>
<!-- Cache multiple components using an array -->
<keep-alive :include="['Dashboard', 'Settings']">
<component :is="currentComponent"></component>
</keep-alive>
<!-- Exclude specific components from being cached -->
<keep-alive :exclude="['LiveChatWidget']">
<component :is="currentComponent"></component>
</keep-alive>
Cache Control Using Key Attribute
Adding a unique key forces the cached instance to update when the key changes.
<keep-alive>
<component :is="userView" :key="userView + userId"></component>
</keep-alive>
Component Lifecycle Hooks
Cached components gain two additional lifecycle hooks: activated and deactivated.
<template>
<div>
<h2>Data Dashboard</h2>
<!-- Component content -->
</div>
</template>
<script>
export default {
name: 'DataDashboard',
activated() {
// Called when the cached component is inserted into the DOM
this.refreshDataFeed();
},
deactivated() {
// Called when the cached component is removed from the DOM
this.stopDataUpdates();
},
methods: {
refreshDataFeed() { /* ... */ },
stopDataUpdates() { /* ... */ }
}
};
</script>
Practical Example
This example integrates caching with lifecycle management.
<template>
<div>
<button @click="selected = 'NewsFeed'">Load News</button>
<button @click="selected = 'WeatherWidget'">Load Weather</button>
<keep-alive>
<component :is="selected"></component>
</keep-alive>
</div>
</template>
<script>
export default {
data() {
return { selected: 'NewsFeed' };
},
components: {
NewsFeed: {
template: '<div>Latest News...</div>',
activated() { console.log('NewsFeed visible'); },
deactivated() { console.log('NewsFeed hidden'); }
},
WeatherWidget: {
template: '<div>Weather Forecast...</div>',
activated() { console.log('WeatherWidget visible'); },
deactivated() { console.log('WeatherWidget hidden'); }
}
}
};
</script>