Callback for Vue asynchronous components

<template>
    <div>
        <DynamicComponentA></DynamicComponentA>
        <!-- Display DynamicComponentB only after DynamicComponentA is loaded -->
        <DynamicComponentB></DynamicComponentB>
    </div>
</template>

<script>
export default {
    name: "Example Component"
    components: {
        DynamicComponentA: () => import("./DynamicComponentA"),
        DynamicComponentB: () => import("./DynamicComponentB")
    }
};
</script>

I'm trying to asynchronously load two components within a single component, but I need one of them to render only after the other has finished loading. Do you think that's achievable?

Answer №1

To implement a conditional rendering based on a reference within another component, use the v-if directive.

<template>
   <div>
       <AsyncComponent1 ref="component1"></AsyncComponent1>
       <!-- Show AsyncComponent2 only if AsyncComponent1 is rendered -->
       <AsyncComponent2 v-if="$refs.component1"></AsyncComponent2>
   </div>
</template>

Answer №2

To achieve this functionality, you can set up the first component to trigger an event that is caught by its parent component and used to control the visibility of the second component.

<template>
    <div>
        <AsyncComponent1 v-on:completedLoading="componentLoaded"></AsyncComponent1>
        <!-- Show AsyncComponent2 only after AsyncComponent1 has loaded -->
        <AsyncComponent2 v-if="hasLoadedComponent"></AsyncComponent2>
    </div>
</template>

<script>
export default {
    name: "ParentComponent",
    components: {
        AsyncComponent1: () => import("./AsyncComponent1"),
        AsyncComponent2: () => import("./AsyncComponent2")
    },
    data() {
        return {
            hasLoadedComponent: false
        }
    },
    methods: {
        componentLoaded() {
            this.hasLoadedComponent = true;
        }
    }
};
</script>

Inside AsyncComponent1.vue:


...
mounted() {
    this.$emit("completedLoading");
}
...

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

Retrieving information from a JSON file using JavaScript

My code snippet looks like this: { "badge_sets":{ "1979-revolution_1":{ "versions":{ "1":{ "image_url":"https://static-cdn.jtvnw.net/badges/v1/7833bb6e-d20d-48ff-a58d-67f ...

Exploring the best practices for organizing logic within Node.js Express routes

I'm currently utilizing the https://github.com/diegohaz/rest/ boilerplate, but I am unsure about the best practice for implementing logic such as QR code generation and additional validation. My initial thought was to include validation and password ...

Using Python, Scrapy, and Selenium to extract dynamically generated content from websites utilizing JavaScript

I am currently utilizing Python in combination with Selenium and Firefox to extract specific content from a website. The structure of the website's HTML is as follows: <html> <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8"> ...

Even after dynamically removing the class from the element, the Click event can still be detected

My buttons have a design like this: <a class="h-modal-btn branch-modal-btn"> Buy Now </a> The issue arises when I need to remove certain classes and add attributes to these buttons based on the query string in the URL. Skipping ahead ...

I have a question for you: How can I customize the font size in Material-UI TextField for different screen sizes?

I'm facing a challenge in Material-UI where I need to set different font sizes for TextField. While it may be simple in HTML/CSS, it's proving to be tricky in Material-UI. Can anyone help me figure out how to achieve this? The code snippet below ...

Showing the loading screen while waiting for the static Next.js app to load

Looking for a way to implement a loading screen right before the entire static page finishes loading? I'm currently utilizing modules:export to create my static page, but struggling to listen to the window load event since NextJs has already loaded th ...

The custom pagination feature in MUI DataGridPro does not display the rowsPerPageOptions dropdown as expected

I am currently utilizing React in my project. "react": "^18.2.0", "@mui/material": "^5.10.7", "@mui/x-data-grid-pro": "^5.16.0" An issue arises with the visibility of the rowsPerPageOptions dr ...

Using JavaScript to Parse JSON with Carriage Returns and Line Breaks

Utilizing the script below in JavaScript, I am able to extract a JSON string from a different JS file: // code to retrieve JSON data from another JS module var jsonMatch = data.match( /\/\*JSON\[\*\/([\s\S]*?)\/&bso ...

Angular filtering is not functioning as expected

I have the following code in my template: <li class="row timeline-item" data-ng-repeat="item in data | filter:workoutFilter" data-ng-include="getTemplateUrl(item)"></li> And this is what I have in my controller: $scope.workoutFilter = nu ...

What is the recommended TypeScript type for setting React children?

My current layout is as follows: export default function Layout(children:any) { return ( <div className={`${styles.FixedBody} bg-gray-200`}> <main className={styles.FixedMain}> <LoginButton /> { children } ...

Is it possible to customize text or images using the window.location method?

Imagine I have a scenario with 3 unique servers as follows: https://server-1.com https://server-2.com https://server-3.com In my Vue application, I want to dynamically change an image based on the server being used. Can I achieve this by utilizing someth ...

Despite my attempts to force a repaint, the progress bar remained static during intensive tasks

My JavaScript method works fine in Chrome, taking about 2000 ms to iterate over ~200 inputs, insert values, and trigger onchange events. However, it's a different story in IE where it takes about 10000 ms. To show the progress of this process, I deci ...

The Vue @click functionality seems to be malfunctioning on the Edge browser version I am currently using

I am facing an issue where the Vue @click event is not functioning properly in my Edge browser. I have tried several methods to resolve this problem, including: <button @click="test()">Test</button> <SomeComponentWithClickEventThatWorksInOt ...

Easily include Access-Control-Allow-Origin: * in JSON data

My web server hosts a folder (let's say the link is: www.foo.com/json/). Within this directory, there is a json file named foo.json. I am interested in accessing this file from a different website. I attempted to research "CORS," but found it to be q ...

Conditional compilation in Laravel Mix allows for specific code blocks to be

I'm currently working on a Laravel project and I need to introduce some conditional statements. Within the root folder of the project, there's a file called module_statuses.json which contains JSON variables like this: { "Module1": true, ...

Is it possible to receive real-time updates for a specific location in Cesium

I am currently developing a live tracking application using Cesium, and I'm encountering an issue with updating the point location on the map in real-time. Currently, my Cesium viewer successfully receives the data from the server in JSON format and ...

What is causing the list-sorter to malfunction?

This website crashes when executed: <head> <script> var numbersList = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 19, 17, 15, 13, 11, 9, 7, 5, 3, 1]; var orderedList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, ...

Error encountered in Next.js when defining columns for a MUI data grid

Currently, I am integrating MUI Data Grid into a Next.js app under development. While attempting to define a more intricate column structure, I encountered an error: { field: 'home_address', valueGetter: (value, row) => { retur ...

Iterating through a series of Axios requests nested within each other to handle pagination in an

I need help iterating through the API response that includes pagination. Below is a snippet of the API response: { count: 165, next: "http://example.com/name?offset=30&per_page=30", previous: null } Here is my useEffect hook: const [datas, se ...

Javascript datatables do not allow for setting a default column sort

I am encountering an issue where I need to sort the results by a specific column on page load. In this case, I want the initial results to be displayed in descending order based on "RecordDate". However, it seems that the server side is blocking any sort ...