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

Retrieve worldwide data for the entire application in Next.js during the first page load

Within my Next.js application, I am implementing search filters that consist of checkboxes. To display these checkboxes, I need to retrieve all possible options from the API. Since these filters are utilized on multiple pages, it is important to fetch the ...

Searching for the closest jQuery value associated with a label input

As a beginner in JQuery, I am looking to locate an inputted value within multiple labels by using a Find button. Below is the HTML snippet. Check out the screenshot here. The JQuery code I've attempted doesn't seem to give me the desired output, ...

Undefined value is encountered when passing props through the Context API in a REACT application

Exploring My Context API Provider File (Exp file) import react form 'react'; import {createContext} from "react"; export const ContextforFile = createContext(); export function ContextData(props){ let rdata=props.data return( &l ...

Why is my console showing a SyntaxError with JSON.parse and an unexpected character?

I am facing an issue. When I attempt to call a PHP page for some data with specific requested parameters using AJAX asynchronous call, I encounter the following error: SyntaxError: JSON.parse: unexpected character var jsonData = $.ajax({ u ...

Regex pattern to replace the zero preceding two times within a string based on distinct criteria

I need to transform the string XY4PQ43 using regex in JavaScript. The output should be XY04PQ0043. Specifically, I want to add a zero prefix to the first number if it is a single digit to ensure it has 2 digits, and for the second number in the string, I w ...

Unable to retrieve the field value from the Json Object

I have a JSON object that I need to parse and display in a data table, but I'm having trouble reading the contents of the object. Here is my JavaScript function: finalGrid: function(data){ console.log("Final Grid"); var strJson = JSON.strin ...

Mapbox is capable of managing several GEOJSON files by utilizing the loadURL function

I am in the process of creating a map that is designed to load multiple layers from various sources based on a configuration file called config.json. Each layer should trigger a popup when clicked, but oddly enough, I am only able to see the popup for the ...

Receiving alerts about props passed in MUI styled components triggering React's lack of recognition

I have a unique component design that requires dynamic props to determine its styling. Here is an example: const StyledTypography = styled(Typography)( ({ myColor = "black", isLarge = false }) => ({ "&&": { fontSi ...

Adjusting Iframe Dimensions Dynamically with Javascript based on Anchor Location

I am experienced with handling this issue in flash, but I am struggling to figure out how to do it using Javascript and CSS. The problem involves an iframe that does not have an overflow property, and I need to modify its width/height. Is there a simple ...

Having trouble getting Firebase phone number authentication to work with Vue.js

I am currently in the process of developing a new Vue.js application using the Webpack template. Within this app, I have implemented a /sign-in route that displays a component named SignIn. To authenticate users, I am utilizing Firebase Phone Number authen ...

Pass the JavaScript variable and redirect swiftly

One of the functionalities I am working on for my website involves allowing users to submit a single piece of information, such as their name. Once they input their name, it is sent to the server via a post request, and in return, a unique URL is generated ...

Switch out the ajax data in the input field

Is there a way to update the value in a text box using Ajax? Below is my code snippet: <input type="text" id="category_name" name="category_name" value="<?php if(isset($compName)) { echo ucfirst($compName); ...

Replicate and $(document).ready()

My form has required fields that need to be completed. To alert users about blank fields, I have implemented the following code: $(document).ready(function() { $('input.required:text').focus(function() { $(this).css({'background ...

Problem arising from apostrophe usage in Javascript OData request

In my current project, I have a text input field that passes a value through JS to fetch filtered data of names from a JSON file using OData query parameters. However, I've encountered an issue where if a name contains an apostrophe, it results in a ...

Oops! Make sure to explicitly allow the dependency @types/html2canvas by adding it to the "allowedNonPeerDependencies" option

After installing the html2canvas package in my Angular library project, I encountered an error when compiling in production mode using the command ng build --prod. The specific error message is as follows: ERROR: Dependency @types/html2canvas must be exp ...

State dropdown in Angular dynamically updates based on the country selected

I am in search of a contextual state dropdown menu that is linked to the country, ensuring only relevant states are displayed. I have explored these two solutions for guidance in my project. Angularjs trigger country state dependency angularjs dependant ...

What is the best way to incorporate tooltips in SVG?

My teacher wants me to display a tooltip on an SVG circle with links and information when we hover over it. They suggested using jQuery UI, but I've done extensive research and nothing has been able to assist me so far. ...

Directing users to a specific section on another webpage can be accomplished using HTML, JavaScript, or

<nav> <div class='container-fluid'> <h1 class='logo'>Logo</h1> <ul class='list-unstyled naving'> <li><a href='index.html'>Home</a></li> ...

Having trouble getting Vue to properly focus on an input field

I am attempting to use this.$refs.cInput.focus() (cInput being a ref) but it seems to not be functioning as expected. I expect that when I press the 'g' key, the input field should appear and the cursor should immediately focus on it, allowing me ...

What could be causing the VueJS function not to be triggered by the dropdown selection?

I created a simple component called LocaleSwitcher.vue using the Element UI library: <template> <el-dropdown trigger="click"> <div> <i class="el-icon-map-location"></i> </div> < ...