What is the best way to use async await to listen for an event in a child component with Vue-router?

To prevent users from unintentionally leaving an unsaved form, I am looking to implement a custom modal alert system with vue-router.

Although the use of the standard browser alert box is an option,

beforeRouteLeave (to, from, next) {
  const answer = window.confirm('Do you really want to leave? You have unsaved changes!') 
    if (answer) {
      next();
    } else { 
      next(false);
    }
}

I am interested in how I can synchronize this functionality with a custom child modal component's event:

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

    if (response) {
      next();
    } else {
      next(false);
    }
}

Answer №1

When it comes to <code>beforeRouteLeave
, it lacks support for promises. Any promise returned by an async function will be ignored.

In the world of JavaScript, next is a commonly used name for callbacks. According to the official documentation, this callback accepts an argument and should be structured as follows:

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

    if (response) {
        next();
    } else {
        next(false);
    }
}

Answer №2

Managed to get it to function, but unsure if this is the optimal approach:

To start off, store the next function as a data object

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

then, in your modal component, trigger an event and manage it on the parent component

<modal @continueOrCancel="continueOrCancel" />

Execute the function on the parent component

methods: {
  continueOrCancel(e) {
     if (e == "continue") {
        this.nextObj(); // successful execution.
     } else {
        this.nextObj(false); // unsuccessful. Only displays the next function. Attempted with string "false" and integer 0 resulting in the same outcome. 
        this.showModal = false; // what about route lifecycle??
     }
  }
}

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

Making the Select Tag function as an on-click event in JQuery

So I currently have a tab set up that functions as on click links when viewed on desktop. However, for tablet and mobile devices, I need it to be transformed into a select drop down list while maintaining the same functionality. Below is the code used for ...

Discovering nearby intersections within 2 sets of arrays

Imagine having these two arrays: var a = [126, 619, 4192, 753, 901]; var b = [413, 628, 131, 3563, 19]; Is there a way to identify elements in both arrays that are close to each other by a certain percentage? Let's say we have the following functio ...

Saving the initial state value in a variable in Vue.js is a crucial step in managing and

My dilemma involves an object in the Vuex store containing data that I need to utilize within a component. I have successfully accessed the data using a getter in the component. However, I am facing a challenge in preserving the initial value of this objec ...

A variant of setTimeout designed specifically for family members

I am currently working on a program that involves creating a "health" variable which decreases by random amounts at random intervals. This means that a player may encounter scenarios like the following: 5 seconds Lose 20 health 3 more seconds Lose 25 healt ...

What could be causing the audio file not to be received from the front end React to the Python server?

Here is the React code snippet: import React ,{ ChangeEvent, useState } from "react" const FileUpload: React.FC = () => { const [selectedFile, setFile] = useState<File| null>(null); const HandleAudioChange = (event:ChangeE ...

Although AJAX $.post functions properly in the View, it seems to encounter issues when relocated to a separate .js file. Interestingly, all other JQuery functions work

I have recently delved into MVC, JQuery, and AJAX, and encountered a perplexing issue. After completing the initial development of a practice website, I dedicated time to enhance the interactivity using JQuery. Everything was functioning smoothly until I ...

What is the best way to incorporate setTimeout in a loop using Coffeescript?

window.onload = -> boxOrig1 = 10 boxOrig2 = 30 canvasW = 400 canvasH = 300 ctx = $("#canvas")[0].getContext('2d'); draw = (origin,dimension) -> ctx.clearRect(0, 0, canvasW, canvasH) ctx.fillStyle = 'rgb(200,0 ...

Prevent Vue from throwing an error when a component is not defined

Currently, I am working on a component that includes an optional child component within it. <template> <div> <child-component :propA="valueOfA"/> <!-- this child is always present --> <optional-child-component :prop ...

Is there an issue with VUE npm run serve due to Tailwindcss being absent?

A few months back, I embarked on a project using Vue and incorporated Tailwind CSS by running the command (Vue add Tailwind). Recently, when attempting to create a new project with the default Vue3 template using the command vue create project and then na ...

A link is not allowed to be a child of another link

An issue arises in a React.js application Warning: validateDOMNesting(...): <a> cannot be nested under another <a>. Refer to Element > a > ... > a for more information. What is the significance of this warning? How can it be avoided ...

Obtain the IDs of the previous and next list items if they exist?

Hey there friends, I've hit a roadblock and could really use your help. I'm trying to figure out how to get the previous and next list items in a specific scenario. Let's say I have a ul with three li elements, and the second one is currentl ...

Unable to utilize a computed property within the data section

I am working with an array in my data: data () { return { steps: [ { disabled: this.someCheck } ] } } Additionally, I have a computed property: computed: { ...mapGetters({ getFinishedSteps: 'jobFound/getFinishedS ...

Response from the controller upon choosing a value from the selection dropdown

Scenario: In this scenario, there are two tables in consideration: Firm table : ID (string), Firm(string) Firms table: FirmID(string FK), Name(string) The goal is to select a value from the Firm table, pass it to the controller as Firm, and then execut ...

What issues are hindering the successful export of my Vue component packaged with npm?

I created a small local npm package called fomantic-ui-vue with the following main js file: import Vue from 'vue' // Import vue component import button from './elements/button/button.vue' import buttonGroup from './elements/butt ...

What is the best way to obtain the output of a JavaScript function on the server side?

I'm dealing with a JavaScript function that returns an array in this particular format: <script type="text/javascript"> function looping() { var column_num = 1; var array = []; $("#columns ul").not(" ...

angular-recaptcha: Adjusting language based on the website's language update

My website offers three different languages that users can switch between. The language switch functionality is implemented on the client side using JavaScript (AngularJS). I have integrated reCAPTCHA 2 into my website and now I need to update the languag ...

Tips for recognizing users in socket.io?

I'm currently developing a chat application with socket.io. However, one issue I am facing is identifying the sender of a message. Unlike in Express where we have the "req" (request) variable to easily identify users, socket.io does not provide such f ...

What are the steps for applying a Bootstrap class to an element?

I keep encountering this error in the console: Uncaught DOMException: Failed to execute 'add' on 'DOMTokenList': The token provided ('si col-md-4') contains HTML space characters, which are not valid in tokens. Below is a ...

Passing an object using Ionic Vue's router-link

Looking to send an object as a prop to another page using a router-link in Ionic-Vue. When clicking on the link I created, it looks like nothing is getting passed through. Here's the link I currently have: <router-link :to="{ name: 'mov ...

Keep an ongoing execution of a node.js file by sending an HTTP request repeatedly

I am working on a project using node.js and express where I have a file named TCPServer.js that is responsible for polling a TCP/IP server. The goal is to send a single HTTP request to a database, retrieve the IP Address and port number, and then utilize t ...