0
0
Vueframework~30 mins

Keep-alive for caching components in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
Keep-alive for caching components
📖 Scenario: You are building a simple Vue app with two components: HomeView and ProfileView. You want to switch between these views using buttons. To improve user experience, you want to keep the state of each component cached so that when you switch back, the component does not reload from scratch.
🎯 Goal: Create a Vue app that uses the <keep-alive> wrapper to cache the HomeView and ProfileView components when switching between them.
📋 What You'll Learn
Create two components named HomeView and ProfileView with simple content
Create a reactive variable currentView to track which component to show
Use buttons to switch currentView between 'HomeView' and 'ProfileView'
Wrap the dynamic component with <keep-alive> to cache the components
💡 Why This Matters
🌍 Real World
Caching components with <code>&lt;keep-alive&gt;</code> is useful in apps where users switch between views frequently, like dashboards or profile pages, to improve performance and user experience.
💼 Career
Understanding component caching is important for frontend developers working with Vue to build fast, responsive, and user-friendly applications.
Progress0 / 4 steps
1
Create the two components
Create two Vue components named HomeView and ProfileView. Each component should have a <template> with a <div> containing the text "This is Home View" for HomeView and "This is Profile View" for ProfileView. Use the <script setup> syntax for each component.
Vue
Need a hint?

Each component needs a template with a div showing the text. Use <script setup> even if empty.

2
Set up the main app with currentView variable
In your main Vue component (e.g., App.vue), import ref from vue and create a reactive variable called currentView initialized to 'HomeView'. Also import the HomeView and ProfileView components.
Vue
Need a hint?

Use ref to create currentView and set it to 'HomeView'. Import both components.

3
Add buttons to switch views and dynamic component rendering
Add two buttons labeled Home and Profile. When clicked, they should set currentView.value to 'HomeView' or 'ProfileView' respectively. Below the buttons, use the <component> tag with :is="currentView" to render the selected component dynamically.
Vue
Need a hint?

Use @click on buttons to change currentView. Use <component :is="currentView" /> to show the selected component.

4
Wrap the dynamic component with keep-alive
Wrap the <component :is="currentView" /> tag inside a <keep-alive> tag to cache the components when switching between them.
Vue
Need a hint?

Wrap the dynamic component inside <keep-alive> tags to cache it.