0
0
Vueframework~30 mins

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

Choose your learning style9 modes available
Keep-alive for Expensive Components in Vue
📖 Scenario: You are building a Vue app with two components that simulate expensive loading times. You want to switch between these components without losing their state or reloading them every time.
🎯 Goal: Create a Vue app with two components named ExpensiveOne and ExpensiveTwo. Use Vue's <keep-alive> feature to keep these components alive when switching, so their state is preserved and they do not reload.
📋 What You'll Learn
Create two components named ExpensiveOne and ExpensiveTwo with a simple template and a data property count initialized to 0.
Add a button in each component to increment the count value.
Create a main Vue app that switches between these two components using a currentComponent variable.
Wrap the dynamic component with <keep-alive> to preserve component state when switching.
💡 Why This Matters
🌍 Real World
Many apps have components that take time to load or have user input. Using keep-alive helps keep their state so users don't lose data when switching views.
💼 Career
Understanding keep-alive is important for Vue developers to optimize app performance and user experience by avoiding unnecessary reloads.
Progress0 / 4 steps
1
Create two components with a count state
Create two Vue components named ExpensiveOne and ExpensiveTwo. Each should have a template with a heading showing the component name and a paragraph showing a count data property initialized to 0. Add a button that increments count when clicked.
Vue
Hint

Use ref(0) to create the count state in each component's setup() function. Use @click on the button to increase count.

2
Add a variable to track the current component
In the main Vue app, create a ref variable named currentComponent and set it to ExpensiveOne. This will track which component to show.
Vue
Hint

Use ref(ExpensiveOne) to create the currentComponent variable.

3
Add buttons to switch components and use dynamic component
Add two buttons labeled Show ExpensiveOne and Show ExpensiveTwo. When clicked, they set currentComponent to ExpensiveOne or ExpensiveTwo respectively. Below the buttons, add a <component> tag with :is="currentComponent" to show the selected component dynamically.
Vue
Hint

Use @click on buttons to set currentComponent. Use <component :is="currentComponent" /> to show the chosen component.

4
Wrap the dynamic component with <keep-alive>
Wrap the <component :is="currentComponent" /> tag inside a <keep-alive> tag. This will keep the components alive and preserve their state when switching.
Vue
Hint

Wrap the <component> tag inside <keep-alive> tags to preserve component state.