Vue Js warning for changes that have not been saved

Trying to notify the user about any unsaved modifications in my Vue component's

beforeRouteLeave (to, from, next)
route hook. I want to showcase this prompt on navigation or reload:

https://i.sstatic.net/Qga1Z.png https://i.sstatic.net/fONR8.png

My approach involves utilizing the window.onbeforeunload event, however, it's not working as expected:

  beforeRouteLeave (to, from, next) {
    if (!this.changesSaved) {
            const response = window.onbeforeunload = function(e) {
                return 'Are you sure you want to leave? There are unsaved changes!';
            };
          if (response) {
            return next()
          } else {
            return next(false)
          }
    }
    return next()
  }

What am I missing here in terms of syntax?

Answer №1

One possible reason for this issue could be that the windowunload event is not being utilized, which means the window is never truly unloaded. However, I am not entirely certain about this. Based on my understanding of how Vue functions, it is possible that this is the cause.

Perhaps using the confirm method could provide a solution?

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

Answer №2

It is possible that the issue stems from using the beforeRouterLeave hook in a child component of your route component. To resolve this, you may need to trigger that hook directly within your route component.

For a solution, consider defining route navigation guards directly inside route components (the ones passed to the router configuration) with specified options...

For more information, visit the provided reference

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

What's the deal with Unspecified Variables?

Every time I attempt to execute the following code, an error message pops up saying: Error: taxableIncome is not defined and/or Oops! y is not defined let taxableIncome = 80000; if(taxableIncome >37000 && taxableIncome <80001);{ ...

Distinguishing between `notEmpty` and `exists` in express-validator: what sets them apart

I'm confused about the distinction between exists and notEmpty in express-validator as they seem to function identically. ...

When clicking to open the md-select on Angular Material 1.1.0, an unwanted [object object] is being appended

Every time I try to open the md-select input, an [object Object] (string) is added to the body tag. Click here to see the md-select input After clicking the md-select once, this is how the body looks ...

What is the best way to choose just one value from an option that includes two variables?

I have a list of properties with numbers and names displayed in my form options. <b-col md="3"> <b-form-group :label="$t('departmentNumber')"> <b-form-select vuelidate v-model="$v.consumptionCon ...

What is the best way to create a scrollable tbody in an HTML table using React?

In my current project, I am using React, Node, Express, and Postgres to fetch data from a database. The issue I'm facing involves creating a scrollable table within a div that spans the entire screen width. Initially, I had to apply display: block to ...

The v-model attribute is not properly passing through to the child component

I have created a custom <select> component: <!-- Select.vue --> <template> <div class="select" inheritAttrs="false"> <select v-bind="$attrs"> <slot></slot> </select ...

Using the ESNEXT, Gutenberg provides a way to incorporate repeater blocks that

If you're like me, trying to create your own custom Gutenberg repeater block with a text and link input field can be quite challenging. I've spent hours looking at ES5 examples like this and this, but still feel stuck. I'm reaching out for ...

"Troubleshooting: Why isn't my jQuery AJAX POST request successfully sending data to

Here is the jQuery code snippet that I am currently working with: $("#dropbin").droppable( { accept: '#dragme', hoverClass: "drag-enter", drop: function(event) { var noteid = "<?=isset($_POST['noteid']) ? ...

Verify if the element in the array is set to true

Using a simple boolean in a condition is straightforward : var running = true; if(running) {/*do something*/} But what about using a boolean array? Can it be done like this: var running = [false,false,true,false]; if(running[]){/*do something*/} Curren ...

What steps do I need to take to modify a JSON parser?

I need assistance in converting a parser to JSON for a new server response. Previous server response: {"names":[{"name":"Oleg","act":0,"total":0},{"name":"Vitya","act":2," ...

Adjust the CSS for the "a" tag's "title" attribute

I am using jquery.fancybox to create an image modal on my website. I have noticed that I can add a description using the title attribute. However, when the description is too long, the text is displayed on a single line and some of it disappears. How can ...

Trigger a JavaScript notification when a new record is inserted into the database

I'm looking to set up a Javascript alert for users' browsers whenever a new record is added to the database. Here's what I have so far: PHP chatalert.php require("../system/config.php"); $result = mysql_query("SELECT * FROM chat"); $rows = ...

Constructing a React component with a constructor

I am brand new to working with react native and I'm requesting assistance in fixing the code below. Currently, I have a view within a const and I am looking to include a constructor inside the const function. const { width } = Dimensions.get(' ...

What is the best way in jQuery to display a particular div with a unique id when a link is clicked?

I have a div with the following structure: <article id="#pippo">blablabla</article> which I have hidden using jQuery $('article').hide(); Now, I want to create a link menu that displays a specific article id when it's clicked ...

What steps can be taken to safeguard the integrity of document.referrer against alterations by third-party scripts

My website is currently using a third-party script called Chaordic loader.js for product recommendations, but I am facing an issue where it overrides the document.referrer with inaccurate information, causing me quite a headache. Query: Is there a way to ...

The thumbnail image is failing to load, and when I hover over an image, it moves upwards

I seem to be encountering an issue with a website I uploaded for testing. Everything appears to be working correctly when checked locally in Dreamweaver CS6. However, once the site is uploaded, some issues arise. When hovering over the images, a problem is ...

Getting the alt value and text of an <img> tag and placing it into a textarea

I have a textarea that contains the following content: <textarea id="testContent"> <img src="..." alt="value"> My text.... </textarea> I am aware that I can use javascript to specifically target and retrieve the alt value of the img ele ...

What is the best way to retrieve calendar events using Microsoft Graph and NodeJS based on the calendar name?

Is there a way to condense these two API calls into one? Currently, this code uses microsoft-graph-client to first retrieve the ID of a specific calendar and then fetch the events from that calendar. I am looking for a method to combine these into a single ...

Retrieve data from an SQL database and populate an HTML dropdown menu in a web page using PHP

I am a beginner in the world of JavaScript and facing some challenges. I am working with PHP 7 and attempting to retrieve data from an SQL database, specifically a table. My goal is to extract a single column from this table and display it in a dropdown me ...

Header misalignment occurs when the user scrolls up too quickly causing it to display

One interesting feature on my website is that the header disappears as users scroll down the page, but reappears when they start scrolling back up, even if they are halfway down. However, if a user quickly scrolls up and down, there seems to be an issue wi ...