Unraveling Vue Async Components - Harnessing the power of emitted events to resolve

I am looking to create a Vue async component that stays in a loading state until a custom event is triggered. This means it will render a specified loading component until the event occurs.

Here's an example of how I want it to work:

const AsyncComponent = () => ({
  component: () => new Promise( resolve => import('./MyComponent.vue')
    .then(component => component.$emit.on('customLoadedEvent', resolve))
  ),
  loading: LoadingComponent,
  error: ErrorComponent,
  delay: 200,
  timeout: 3000
})

Is it possible to easily configure something like this?

Answer №1

To include the custom event as a prop, you can follow this method:

<template>
  <div v-if="updating">
    <div v-if="!error">
      <!-- content will be displayed here, such as a loading indicator -->
    </div>
    <div v-if="error">
      <p>Oops, something went wrong</p>
    </div>
  </div>
</template>
<script>
export default {
  props: {
    customEvent: {
      type: any, // potentially Function? it's uncertain
      required: true,
    }
  },
  data() {
    return {
      error: false,
      updating: false,
    };
  },
  mounted() {
    this.updating = true;
    this.customEvent()
      .then((res) => {
        // carry out actions
        this.updating = false;
      })
      .catch((err) => {
        console.log(err);
        this.error = true;
      });
  }
}
</script>

This component triggers customEvent in the mounted lifecycle hook. Confirm if this behavior aligns with your requirements.

To utilize the component, use the following syntax:

<CustomLoadingIndicator :customEvent="someEvent" />

You may consider adding a close button. Regardless of how you clear the component (possibly using setTimeout in the lifecycle hook), ensure to reset the updating and error data properties.

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

Exploring the process of updating computed variables in Vue.jsDiscovering the

All: As a newcomer to Vue, I have encountered a challenging question that I hope someone can help me with: I created a Vue instance as an event bus, like this: var bus = new Vue({ data:{ list:[] }, methods:{ getUpdatedList(){ ...

Using app.use in Express/node.js for routing causes the client to experience excessive delays

After setting up the server-side code in app.js, I encountered an issue: console.log("Server started. If you're reading this then your computer is still alive."); //Unnecessary test command to make sure everything works. var express = require("expre ...

What is causing the initial activation of the <button> within a form?

Within my <form>, I have included 2 submit buttons. The first button looks like this: <button class="regular" id="geocodesubmit" style="height:40px;">Set Location</button> The second button looks like this: <button type="submit" ...

Browser encountering HTTP response that has been shorted extensively

When making an HTTP post request using axios, I am encountering an issue where the body of the response is a large 4MB string. axios({ method: 'POST', url: url, data: data, headers : headers, }) .then(function (response) { co ...

How can I utilize the context menu feature within a Material React Table row?

I am looking to implement a context menu for each row of the MUI Table, but I haven't found a suitable example. Is there native support for row-level context menus in the MUI Table, or is it possible to add this functionality per row? For reference, ...

Passing an array of ID's between two components in Angular: A comprehensive guide

Greetings fellow readers, I have encountered a new challenge in my Angular project. I need to pass an array of IDs from one component to a completely unrelated component. Most solutions suggest using ViewChild, Input, or Output, but since the components ar ...

The xModal window will only pop up once, after which a page refresh is required

My modal window opens when a user clicks on a div, but I'm having an issue. The modal window doesn't reopen when I click on the div again. Here is my code: <div onclick="document.getElementById('id01').style.display='block&apos ...

Form values not being transmitted correctly in Ajax POST request

I'm facing an issue with my form submission through AJAX where the values are coming out incorrect. Strangely, when I use a normal POST submit it works perfectly fine! <script type="text/javascript"> $(function () { $('#B ...

Ways to determine if an image has a designated width/height using JavaScript (jQuery)

Similar Question: How can I retrieve the height and width of an image using JavaScript? Typically, we can determine the image width using $('img').width() or $('img').css('width') when a width is specified as shown below ...

Utilize a map image as a texture on a plane within a personalized shader in THREE.js

I'm currently facing an issue where I need to load two images as textures, blend between them in the fragment shader, and apply the resulting color to a plane. However, I am struggling to even display a single texture properly. My process for creatin ...

The image is experiencing difficulty loading from the Express static directory

Having some trouble with image loading... I've noticed that images are loading fine from the local folder, but not from the uploads folder which is set to be static. I've been attempting to upload a file from the browser. The upload and save pr ...

The prop type for `rows` is invalid in `ForwardRef(DataGrid)`. It was supplied as an object instead of the expected array

Hello there! I'm puzzled as to why my grid table isn't displaying data even though I can confirm that I am receiving data from the API response. I'm wondering what might be wrong with my code. Below is my current code along with the returned ...

Issues with fetching data from a Drupal module using an Ajax call

I have created a custom module in Drupal where the .js file is supposed to make an ajax call to a .module file. However, I am facing issues as the ajax call is not functioning properly. Can someone please assist me with this? Below is my .js file: // Jqu ...

Incorporating Ajax to allow users to choose an option from a selection for

I want to populate a dropdown menu with values received from an ajax call in the form of a json array. However, the current code results in an empty select element being created. $.ajax({ type: "GET", url: "/wp-content/gta/search_airport.php", data: ...

jQuery Validation is not functioning correctly

I am facing an issue with implementing jQuery.Validation. I have written a script and included all JS files below, but for some unknown reason, the validation always returns that the form is valid. Below is the JavaScript code I am using: $(document).rea ...

What is the best way to ensure that all the divs within a grid maintain equal size even as the grid layout changes?

I have a grid of divs with dimensions of 960x960 pixels, each block is usually 56px x 56px in size. I want to adjust the size of the divs based on the changing number of rows and columns in the grid. Below is the jQuery code that I am using to dynamicall ...

What sets apart .create from .save in mongoose?

A while ago, I completed a bootcamp course on Express and Mongoose on Udemy. In the course, we learned how to add new fields to data by writing code like this: var playground = require("../models/playground.js"); route.post("/", middleware.isLoggedIn,fun ...

What is the best way to navigate to a specific location on a web page?

After clicking the "Add comment" link, a comment form popped up using Ajax. I now need assistance with scrolling to it, can you please help me out? ...

Leveraging the $dirty property in AngularJS to determine if any changes have been made to a form

Recently, I've been attempting to determine if my form is being edited by monitoring certain fields. I've come across $dirty as a potential solution for this task, but unfortunately, I'm struggling to identify what exactly I'm overlooki ...

Text that appears automatically in an input field

I've searched high and low, but I just can't seem to find a solution that works for me. What I need is a way to automatically populate a HTML text field with default text when the page loads. This default text should ideally be a PHP variable and ...