0
0
Vueframework~30 mins

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

Choose your learning style9 modes available
Lazy Loading Routes in Vue
📖 Scenario: You are building a Vue app with multiple pages. To make the app faster, you want to load each page only when the user visits it. This is called lazy loading routes.
🎯 Goal: Create a Vue router setup that lazy loads two routes: Home and About. Each route should load its component only when visited.
📋 What You'll Learn
Create a routes array with two routes: / for Home and /about for About
Use dynamic import syntax to lazy load the Home and About components
Create a Vue router instance using createRouter and createWebHistory
Export the router instance as default
💡 Why This Matters
🌍 Real World
Lazy loading routes helps make Vue apps faster by loading pages only when needed, improving user experience especially on slow networks.
💼 Career
Understanding lazy loading routes is important for frontend developers working with Vue to optimize app performance and scalability.
Progress0 / 4 steps
1
Set up the routes array
Create a constant called routes that is an array with two objects. The first object has path: '/' and name: 'Home'. The second object has path: '/about' and name: 'About'.
Vue
Need a hint?

Think of routes as a list of pages. Each page has a path and a name.

2
Add lazy loading to route components
Update the routes array so that each route has a component property. Use dynamic import syntax: for Home, use () => import('./components/Home.vue'). For About, use () => import('./components/About.vue').
Vue
Need a hint?

Use arrow functions with import() to load components only when needed.

3
Create the Vue router instance
Import createRouter and createWebHistory from 'vue-router'. Then create a constant called router by calling createRouter with an object that has history: createWebHistory() and routes.
Vue
Need a hint?

Vue Router needs a history mode and the routes list to work.

4
Export the router instance
Add a line to export the router constant as the default export.
Vue
Need a hint?

Exporting the router lets your Vue app use it.