[Vuejs]-How can I async await for an event in a child component? Vue-router

1👍

beforeRouteLeave isn’t promise-aware, a promise that async function returns is ignored.

next is a common name for a callback in JavaScript ecosystem. As the documentation shows, it accepts an argument. It should be:

async beforeRouteLeave(to, from, next) {
    const a = await this.showModal();

    if (a)
      next(); 
    else
      next(false); 
}

0👍

Got it working but not convinced this is the best solution:

First, save the next function as a data object

beforeRouteLeave (to, from, next) {
   if (this.$store.state.product.unsavedChanges) {
       this.nextObj = next; // save next function as a data object  
       this.showModal = true;
    } else {
        next();
    }
}

then in your modal component, emit an event and handle it on your parent component

<modal @continueOrCancel="continueOrCancel" />

Fire the function on your parent component

methods: {
  continueOrCancel(e) {
     if (e == "continue") {
        this.nextObj(); // works.
     } else {
        this.nextObj(false); // does not work. Only logs the next function. Also tried with string "false", and 0 which produces the same result. 
        this.showModal = false; // continue, but what about route lifecycle ??
     }
  }
}
👤Dazzle

Leave a comment