0
0
Vueframework~30 mins

Lazy loading components in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
Lazy Loading Components in Vue
📖 Scenario: You are building a Vue app that shows different sections on demand. To make the app faster, you want to load each section only when the user needs it.
🎯 Goal: Build a Vue app that lazy loads two components: ProfileSection and SettingsSection. The app should load these components only when the user clicks buttons to show them.
📋 What You'll Learn
Create two simple Vue components: ProfileSection and SettingsSection
Set up a Vue app with buttons to show each section
Use Vue's lazy loading syntax with defineAsyncComponent to load components on demand
Display the chosen component when its button is clicked
💡 Why This Matters
🌍 Real World
Lazy loading components helps make web apps faster by loading only what the user needs, reducing initial load time.
💼 Career
Many modern Vue apps use lazy loading to improve performance and user experience, a valuable skill for frontend developers.
Progress0 / 4 steps
1
Create the two Vue components
Create two Vue components named ProfileSection.vue and SettingsSection.vue. Each should have a simple template with a <div> containing the text Profile Section Loaded and Settings Section Loaded respectively.
Vue
Hint

Each component needs a <template> with a <div> showing the exact text.

2
Set up the main Vue app with buttons
In App.vue, create two buttons with @click handlers named showProfile and showSettings. Also, add a data property called currentSection initialized to an empty string.
Vue
Hint

Use ref to create currentSection. Write two functions to update it when buttons are clicked.

3
Lazy load the components using defineAsyncComponent
In App.vue, import defineAsyncComponent from 'vue'. Create two constants ProfileSection and SettingsSection using defineAsyncComponent that load './ProfileSection.vue' and './SettingsSection.vue' respectively.
Vue
Hint

Use defineAsyncComponent with arrow functions that import the components.

4
Display the lazy loaded component based on user choice
In the App.vue template, use <component :is="..." /> to show ProfileSection when currentSection is 'profile' and SettingsSection when it is 'settings'.
Vue
Hint

Use the <component> tag with :is binding to switch components based on currentSection.