What is the best way to implement lazy loading for a Vue Component?

I've been working on implementing lazy loading for a Login component by using <Suspense> and <template> with default and callback. Everything seems to be functioning properly, except that the Loading component does not disappear after the main component has loaded.

Here is an excerpt from my router.js file:

import { createWebHistory, createRouter } from 'vue-router'

const Login = () => {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve(
                import ('./components/pages/auth/Login'),
            )
        }, 1000)
    })
}
const Register = () => {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve(
                import ('./components/pages/auth/Register'),
            )
        }, 1000)
    })
}

const routes = [{
        path: '/login',
        name: 'login',
        component: Login,
    },
    {
        path: '/register',
        name: 'register',
        component: Register,
    }
]

const router = createRouter({
    history: createWebHistory(),
    routes: routes
})

export default router

The root component file, App.vue, looks like this:

<template>
    <div>
        <Suspense>
            <template #default>
                <RouterView />
            </template>
            <template #fallback>
                <div>
                    <h1>Loading....</h1>
                </div>
            </template>
        </Suspense>
    </div>
</template>
<script>
export default {
    components: {

    }
}
</script>
<style scoped>
div {
    height: 100%;
    width: 100%;
    background-color: black;
}

h1 {
    font-size: 30px;
    font-weight: bold;
    color: white;
}
</style>

After the component loads, the Loading background should disappear but it doesn't. Here's how it looks: The black background persists even after the component has loaded. Click here for a visual reference

Answer №1

As stated in the official documentation, the recommended approach is to use a function with dynamic import for lazy loading:

// Instead of importing UserDetails directly
// import UserDetails from './views/UserDetails'
// Use a function for dynamic import
const UserDetails = () => import('./views/UserDetails')

const router = createRouter({
  // ...
  routes: [{ path: '/users/:id', component: UserDetails }],
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A guide on getting the `Message` return from `CommandInteraction.reply()` in the discord API

In my TypeScript code snippet, I am generating an embed in response to user interaction and sending it. Here is the code: const embed = await this.generateEmbed(...); await interaction.reply({embeds: [embed]}); const sentMessage: Message = <Message<b ...

Element that emulates a different element in HTML

Is it possible to have one element that can control and change multiple clone elements, mimicking every change made to the original? While JavaScript & jQuery can easily achieve this, most solutions involve separate variables or instances for each element ...

typescript unable to use module as variable in import statement

Having trouble importing a variable from another file in TypeScript and assigning an alias name. I keep getting an error saying the alias name is not defined. For example: import { headerItems as TestHeader } from './headers'; Typescript versi ...

Engaging Floor Layout

Currently, I am in the process of developing an interactive floorplan for an office project. The main objective is to provide a user-friendly interface where individuals can search for a specific employee and have their respective office location highlight ...

Alter the navigation background when moving between sections on a one-page website

I need to ensure that the background of the navigation remains transparent on the "home" section. However, when switching to other sections, the background color of the navigation becomes permanently black. <header class="clearfix"> <nav> ...

Troubleshooting the malfunction of jQuery's change() function

There are three HTML select tags on my page. I want these three select tags to function as follows: When I change selectA, selectB should automatically update based on the selection in selectA. Similarly, when an option in selectB is created, changing se ...

Looking to verify characters, numbers, and special characters with jQuery's regular expression feature?

Currently, I am facing a challenge in validating the password field to allow characters, numbers, and special characters. It is essential that the password consists of exactly 8 characters. Despite searching online for a solution, I have been unsuccessful ...

Error: cannot use .json data with `filter` method from WEBPACK_IMPORTED_MODULE_2__["filter"]

There seems to be an error occurring when attempting to retrieve data from a JSON file in the specific line of code selectedEmployee: employeeList.data.Table[0], An issue is arising with TypeError: _employeeList_json__WEBPACK_IMPORTED_MODULE_2__.filter ...

What is the best way to optimize my ExpressJS + Sequelize files for proper compatibility with Jest testing framework?

For the past few years, I have been developing an ExpressJS server application for internal use at my workplace. This application serves as a clinical decision support tool utilized in various hospitals. As the application has grown significantly in size, ...

Checkbox fails to trigger onChange when the checked value is controlled by state management

Currently, I am working with a material-ui Table and have been in the process of implementing multi-select functionality on it. The behavior I am aiming for my multi select to exhibit is as follows: Checkboxes should only appear at the beginning of a ro ...

Ways to retrieve the most recent state in a second useEffect call?

Currently, I am encountering a situation where I have implemented two useEffect hooks in a single component due to the presence of two different sets of dependencies. My challenge lies in the fact that even though I update a state within the first useEffec ...

How is it that a callback function can successfully execute with fewer arguments provided?

Code I'm really intrigued by how this code functions. In the verifyUser function, it passes a callback function as the fourth argument to the verifyToken function. However, upon examining the verifyToken function itself, I noticed that it only has th ...

Tips for creating curved Extjs area and line charts with a gentle radius to soften the sharp curves

I have been working on a mixed charts component for Extjs, and I noticed that the curves appear too sharp. I am unable to find a configuration option to add radius to the curves. If anyone has experience with this issue, could you please share a method t ...

Obtaining objects from a Meteor collection on the server triggers a "Must have Fiber to proceed" error

As a beginner in creating meteor apps, I am working on a project that involves querying git issues from a specific repository. The goal is to generate tasks from these issues after retrieving them using the Github API. However, I keep encountering an error ...

A guide to sorting an object with integer keys by its values using JavaScript

I am facing an issue with sorting a map by values instead of keys. No matter what I do, it always ends up getting sorted by the keys. On the server side, I have a map that is already sorted. When I send this map to JavaScript using JSON, it gets re-ordere ...

Is there a reason why the integration of OnsenUI with Vue using vue-onsenui and v-ons-segment is not functioning

I am experiencing an issue with OnsenUI and VUE vue-onsenui v-ons-segment. Instead of displaying a button bar in a row as expected, I am seeing standard buttons. The problematic code resides in a customized Monaca CLI project utilizing the minimal VUE tem ...

Identify the Presence of Hover Functionality

For a while now, the trend has been leaning towards feature detection. I am interested in determining whether a visitor's browser supports the :hover pseudo class. With many mobile devices not supporting hovering, I want to adjust my event listeners a ...

Is it possible to have the ShowHide plugin fade in instead of toggling?

I'm currently utilizing the ShowHide Plugin and attempting to make it fade in instead of toggle/slide into view. Here's my code snippet: showHide.js (function ($) { $.fn.showHide = function (options) { //default variables for the p ...

Vue 3 - unable to connect attributes to any element

Can you assist me in understanding how to bind attributes with Vue 3? I have an app that functions well on its own, but when I incorporate it into XML <content type="html>" VUE APP </content>, the bindings do not work as expected. T ...

Embed Text inside an HTML Canvas

As someone who is relatively new to working with html canvas, I am having a bit of trouble when it comes to containing text within the canvas area. Specifically, I am pulling text from a textarea and displaying it on the canvas, but it seems to stay as one ...