Frontend Development Projects with Vue.js 3 - Second Edition by Maya Shavin & Raymond Camden & Clifford Gurney & Hugo Di Francesco

Frontend Development Projects with Vue.js 3 - Second Edition by Maya Shavin & Raymond Camden & Clifford Gurney & Hugo Di Francesco

Author:Maya Shavin & Raymond Camden & Clifford Gurney & Hugo Di Francesco
Language: eng
Format: epub
Publisher: Packt
Published: 2023-12-15T00:00:00+00:00


Tips on loading components for route configuration

Indeed, we need to import the component to tie it to the targeted route in the same index.js file. The classic and most popular way is to import it at the top of the file as follows:

import Home from '../views/HomeView.vue'

Often, we add this code line under the main imports as shown in Figure 7.3:

Figure 7.3 – Importing the HomeView component on line 2 – src/router/index.js

However, a more efficient way is to lazy-load the component.

Lazy loading, also known as on-demand loading, is a technique that aims to optimize the content of a website or web application at runtime. It helps to reduce the time consumption and number of resources required to download an application on the first load.

This optimization is critical to ensure the best user experience possible, where every millisecond of waiting matters. Besides this, lazy loading also enables better code-splitting at the route level and performance optimization in large or complex applications.

We can lazy-load the component by using Vite (and Rollup). Instead of importing the AboutView component into the top of the file, as we did with HomeView (see Figure 7.3), we can dynamically add the following right after defining the name of the about route instead:

component: () => import('../views/AboutView.vue')

Here, we dynamically lazy-load the AboutView view component for the about route. During compilation, Vite generates a separate chunk with the designated name (about) for the target route and only loads it when the user visits this route.

In most cases, since the user will likely land on the default path on the first go, it is better not to lazy-load the default component (HomeView in our app) but to import it in the usual way. Hence, the tip here is to determine which elements should be lazily loaded when designing your routing and combine the two methods for the most benefit.

We will now see how to set up the router instance.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.