Tips for handling a fulfilled promise within a Vue event handler

Here is a sample component code:

<template>
  <div class="text-center">
    <v-dialog
      v-model="dialog"
      width="500"
    >
      <template v-slot:activator="{ on, attrs }">
        <v-btn
          color="red lighten-2"
          dark
          v-bind="attrs"
          v-on="on"
        >
          Click Me
        </v-btn>
      </template>

      <v-card>
        <v-card-title class="headline grey lighten-2">
          Privacy Policy
        </v-card-title>

        <v-card-text>
          Some text
        </v-card-text>

        <v-divider></v-divider>

        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn
            color="primary"
            text
            @click="handleAsyncAction"
          >
            I accept
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </div>
</template>

<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";

@Component()
export class MyDialog extends Vue {
 dialog: booolean = false;
 
  async handleAsyncAction() {
  const value = await this.$emit('click'); // you can't really do that
  if(value === 'x') {
    dialog = false; //<--- then close
  } else {
   alert('error!')
  }
 }
}
</script>

A hypothetical parent component using the above `MyDialog` component:

<template>
 <div>
    <MyDialog @click="makeSomeAjaxRequest($event)"
 </div>
</template>

<script type="ts">
import Vue from "vue";
import Component from "vue-class-component";
import MyDialog from "./MyDialog"

@Component({
  components: { MyDialog }
})
export default class ParentComponent extends Vue {
  async makeSomeAjaxRequest() {
    const data = await fetch('http://example.com');
    return data.toString();
  }

}
</script>

In React, passing functions from parent to child is common practice. However, in Vue, it is not the recommended way. What would be the Vue approach to have the child component wait for the asynchronous call to complete?

Answer №1

Within Vue components, all event listeners are stored conveniently under this.$listeners

Utilizing this feature allows you to trigger the function without emitting an actual event:

// ExampleComponent
async handleAsyncEvent() {
  //@ts-ignore as Vue 2's TS definitions support this behavior
  const result = await this.$listeners.click();
  if(result === 'x') {
    closeDialog(); //<--- then close
  } else {
   alert('error!')
  }
 }
}

If you want to explore a practical application of this concept, check out the article titled Reacting to Promises from event listeners in Vue.js

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

Saving solely the content of an HTML list element in a JavaScript array, excluding the image source

One issue I am facing is with an unordered list in HTML which contains items like <ul id="sortable"> <li class="ui-state-default"><img src="images/john.jpg">John</li> <li class="ui-state-default"><img src="images/lisa.jpg ...

Adding tags or slots to input fields in Vue

When working with Vue, I have implemented a basic input text field for user input. My goal is to generate removable slots based on the text entered by the user. There is a button labeled "add slot" which allows users to add their desired input. Please refe ...

Troubleshooting Autocomplete User Interface Problems

I am currently working on a website user interface and I have encountered an issue specifically in IE7. When searching for a company, the display is not showing up correctly, as demonstrated in the image below. This problem only occurs in IE7, it works fi ...

What is the best way to incorporate javascript assets selectively in SailsJS?

How can I selectively include javascript assets in a Sails.js application? For example, if I have an admin page with admin.js in the assets/js directory, how can I prevent admin.js from loading on the public index page? I know I could move the js to the ...

The Angular component fails to retrieve data from a subscribed service when the data is being fetched from the sessionStorage

Within my Angular application, there exists a service that handles incoming objects by adding them to a list of objects, then saving the updated array to sessionStorage. This service also sends the updated list to another application that is subscribed to ...

passport.authenticate method fails due to empty username and password values

I seem to be making a simple mistake while following a tutorial. Even though I believe I have followed all the steps correctly, when I submit the login form, I get redirected to the "failureRedirect" page. When I checked the source code in the passport mod ...

Tips for handling an AJAX form submission with various submit buttons and navigating through Laravel routes

I am having trouble getting the form below to submit to the database. The issue arises when trying to use AJAX to submit the forms. The problem seems to occur at this point: $(i).submit(function(event) { Can someone help me figure out what I am doing wr ...

Using HTML and JavaScript to create a link that appears as a URL but actually directs to a JavaScript function

I am working on an HTML page and I am trying to create a link that appears to go to 'example.html' but actually goes to 'javascript:ajaxLoad(example.html);'. Here is what I have tried: <a href="example" onclick="javascipt:ajaxLoad( ...

How can I style the inner div by adding a class to the first div?

In my project, I have a list of elements that are generated dynamically, all styled the same way but with different content. The first element has a specific styling, and if it doesn't render, I want the second element to inherit that styling. < ...

Minimize the length of the styled-component class name in the upcoming iteration

Dealing with styled-components in Next along with React can pose a challenge when it comes to ensuring proper rendering of the styled components. To tackle this issue, Next offers the compiler.styledComponents flag within the next.config.js file like so: c ...

Response: "Merge Button Not Found Error in GitHub API Pull Request Merge"

When attempting to utilize the Github Merge Pull Request (Merge Button), I am encountering a 404 Not Found response both in Postman and my application. Despite confirming that the :owner, :repo, and :number are correct. https://api.github.com/repos/:owner ...

Can file input buttons be custom styled?

Since I am using Material-UI, the traditional methods are not working for me. I have a form with two buttons positioned next to each other. One button is an "Upload File" input for users to upload a file, and the other is a submit button. I want both butto ...

Remove an owl carousel using Laravel, Vue.js, and Axios

I've implemented a sleek slider on my website to showcase images with accompanying text to visitors. The slider utilizes owl carousel within a vue component and is functioning properly. Now, I'm attempting to add a delete button so that users who ...

Caution: The file path in node_modules/ngx-translate-multi-http-loader/dist/multi-http-loader.js relies on the 'deepmerge' dependency

My micro-frontend angular project is using mfe (module federation). I recently updated it from angular 13 to 14 and encountered some warnings such as: node_modules\ngx-translate-multi-http-loader\dist\multi-http-loader.js depends on ' ...

Utilizing Javascript to Open a New Tab from Drupal

I'm attempting to trigger the opening of a new tab when a specific menu link is clicked within a Drupal website. My initial approach was to incorporate JavaScript directly into the content of the page, but unfortunately this method has not been succes ...

"Angular fails to retrieve any data from JSON API, returning a blank response

My ng-repeat function is not returning anything, and as a beginner in Angular, I am struggling to identify the error. Despite thorough error checking, I can't seem to figure out what's going wrong here. (function() { var app = angular.module( ...

Loading images in advance using jCarousel

I need help with preloading images on a jCarousel that loads a JSON feed and generates necessary HTML. Can anyone suggest a way to accomplish this task efficiently? $(".banner ul").jcarousel({ itemLoadCallback:loadTopBanner, auto: 6, wrap: ...

Javascript object attributes

Could you retrieve the value of one object property based on the value of another property? For instance, in an SQL query, is it possible to fetch the id from the object where the object.name equals "somename"? I am trying to obtain the id of a particula ...

What benefits does the useCallback() hook offer in addressing function equality concerns within React?

Exploring useCallback() Hook In my quest to grasp the inner workings of the useCallback() hook in React and its significance in resolving function equality concerns, I came across a blog post shedding light on the topic. However, there are still some aspe ...

JavaScript: A guide on sending an uploaded email to a web service in byte array format

Scenario: My website is built using EXTJS6. I have a web service that requires the uploaded email to be sent in byte array format. Inquiry: What is the process for converting a .msg file to a byte array using JS (or EXTJS)? Can we treat it as a simple bin ...