Leveraging async elements alongside loading and error components in Vue Router

I am attempting to achieve the following:

import Vue from "vue";
import Router from "vue-router";
import Home from "./views/Home.vue";
import LoadingComponent from '@/components/Loading.vue';

Vue.use(Router);

const router = new Router({
    routes: [
        {
            path: "/",
            name: "home",
            component: Home
        },
        {
            path: "/about",
            name: "about",
            component: () => ({
                component: import("./views/About.vue"),
                loading: LoadingComponent,
                delay: 1
            })
        }
    ]
});

export default router;

However, the loading component never appears, even when I set the network to Slow 3G. This issue only occurs when I use async components in the router; elsewhere, the loading component displays after the designated delay.

Is this a limitation of Vue Router or am I overlooking something in my implementation?

Answer â„–1

After delving into github issues related to vue-router, I stumbled upon the solution to my question. It appears that using async components isn't as straightforward as the documentation suggests.

As stated in this online discussion:

Vue Router currently only allows routes to resolve to a single component. To work around this limitation, a helper function can be created to generate an intermediary component, like the one below:

const createLazyRoute = AsyncView => {
    const AsyncComponent = () => ({
        component: AsyncView,
        loading: Spinner
    });

    return Promise.resolve({
        functional: true,
        render(h, {data, children}) {
            // Pass any props or children to the view component.
            return h(AsyncComponent, data, children);
        }
    });
};

This intermediary component can then be used with Vue Router as follows:

const router = new Router({
    routes: [
        {
            path: "/",
            name: "home",
            component: Home
        },
        {
            path: "/about",
            name: "about",
            component: () => createLazyRoute(import("./views/About.vue"))
        }
    ]
});

Hopefully, this method proves to be beneficial for others facing a similar challenge like I did!

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

The list in Jquery UI Autocomplete is not updating correctly

Currently, I am using jQuery UI Autocomplete in conjunction with WebSockets to fetch and display a list of options. Each time a keystroke is detected on the input field (.keyup()), a call is made to retrieve the list. However, I have encountered an issue w ...

Creating a bucket in Autodesk Forge Viewer is a straightforward process with the Forge API

I am currently facing an issue while trying to create and upload a new bucket for storing models. I keep getting a 400 Bad Request error, even though I managed to make it work in a previous project using a different method. Strangely enough, I now encounte ...

Default exports are not supported in TypeScript

I'm encountering issues with my Laravel + Vite + Vue 3 project. I followed the installation instructions in the documentation and everything works fine when the project is separated from Laravel and Vite. However, I'm facing a problem where TypeS ...

Experiencing a 400 error while transitioning from ajax to $http?

I am facing an issue while trying to make a GET request using $http instead of ajax. The call functions perfectly with ajax, but when attempting the same with $http, I encounter a 400 (Bad Request) error. I have referenced the Angular documentation and bel ...

Simply touch this element on Android to activate

Currently utilizing the following code: <a href="http://www...." onmouseover="this.click()">Link</a> It is evident that this code does not work with the Android Browser. What javascript code will function properly with the Android Browser as ...

Filtering Dropdown List in AngularJS with a Text Input Field and a Submit Button for Filtering Option Values

After exploring , I discovered a feature that enables users to type in a text box and filter results in a pseudo-dropdown. My goal is to enhance this functionality or come up with a better approach for users to type and filter select box options, ultimate ...

Include the await keyword within the .then block

I'm trying to execute an await after receiving a response in the .then callback of my code: const info = new getInfo(this.fetchDetails); info .retrieve() .then((res) => { const details = this.getLatestInfo(res, 'John'); }) .ca ...

Basic looping through a single item to showcase its properties and data

I have an object that looks like this: const people = { men: 4, women: 2, total: 6, participants: { 1: 4, 2: 1, 3: 0 } }; I am looking to display the following result: 1 participants count 4 2 participants count 1 3 participan ...

Placing the IconButton within an AppBar Component using React-JS

Trying to position two IconButtons within a Toolbar, one on the right side and the other on the left side. However, both are ending up on the right side. Here's my code: <AppBar position="fixed" > <Toolbar> <Ic ...

What is the best way to delay the loading of a JavaScript script on my website for 20 or 30 seconds

Is there a way to load the following JavaScript ad after 30 seconds on my WordPress site? <script type="text/javascript"> var uid = '219412'; var wid = '586053'; var pop_tag = document.createElement('script ...

Is there a way I can turn off the dragging functionality in my situation?

Is there a method to disable the dragging functionality within a draggable element? $('#dragitem').draggable({ scroll : false, drag: function(event, ui){ //check if condition is met if(†...

Executing a function automatically when a component loads in react-redux can be achieved by utilizing useEffect hook in functional components

I have developed a webpage specifically designed to manage a "Cart" feature, with Cart details being fetched from a database. Upon clicking the "Click me" button, all the retrieved data is displayed within a react component. My goal now is to showcase the ...

Ways to determine if an element has exceeded its container's boundaries

After creating the codesandbox, I have developed a webapp that heavily relies on user input. To keep it simple for demonstration purposes, I am displaying various authors on an A4 formatted page using `page` and `font-size` with the `vw` unit for responsiv ...

Creating a dynamic form field using JavaScript

I'm struggling with a JavaScript issue that requires some assistance. I have a form sending an exact number of inputs to be filled to a PHP file, and now I want to create a preview using jQuery or JavaScript. The challenge lies in dynamically capturin ...

Integrate retrieved JSON data using Ajax into D3 visualizations

Could someone please guide me on how to incorporate fetched JSON data using Ajax into D3? I've integrated this example here into my project and now I just want to populate the radial layout with my own data. The image below shows the current bilevel r ...

Error in AngularJS: Unable to access property 'get' as it is undefined

Upon examining my App, I found that it is structured as follows: var app = angular.module('cockpit', ['tenantService', 'ngMaterial', 'ngMdIcons']); The controller associated with my App appears like this: angula ...

What are the steps to execute a file on localhost using an HTML page?

Currently, I have an HTML file that leverages the Google Calendar API javascript to read the next event on my calendar. The functionality works flawlessly when manually inserting a specific URL in a browser address window, which triggers a GET request in a ...

Is there a way to make the submit button navigate to the next tab, updating both the URL and the tab's content as well?

I am encountering an issue with my tabs for Step1 and Step2. After pressing the submit button in Step1, the URL updates but the component remains on tab1. How can I resolve this so that the user is directed to the Step2 tab once they click the submit butto ...

Is there a way to retrieve the $state object from ui router in the console?

I attempted to modify the route from the console by using this method to access the $state object: $inject = angular.injector(['ng', 'ui.router']); $inject.get('$state').go Unfortunately, I encountered an error: Uncaught Er ...

Identifying overflow of text or elements in JavaScript during execution

The website I'm working on has a unique design that requires users to scroll horizontally using the Arrow Keys instead of swiping. To achieve this, I must constantly check for overflow in text or elements each time a new page is loaded, and if necessa ...