DEV Community


Prevent routing if unsaved changes exist [VueJS]

Josef Biehler
I am a tall (1,95m) coding & drawing enthusiast that likes all type of coding and drawing cartoons. I like to work (coding & drawing) on the go with my surface #cypress #js #csharp
・2 min read

Let's say you have a input field and routes configured:

How can you avoid that the user navigates to a route if the inputfield contains unsaved text? I made a few tries to find a solution for that but did not found anything. So here is what I have done to solve this problem.

Find the full runnable example here: Click me!


First, define a new global function:

let isRouteChangeBlocked: boolean = false;

export function blockRouteChange(set?: boolean): boolean {
    if (arguments.length == 1) {
        isRouteChangeBlocked = !!set;
        return isRouteChangeBlocked;

    return isRouteChangeBlocked;

Then use it to set the flag after the user make some input:

  private inputChange(to: string) {
    if (to && to.length > 0) {
    } else {

After a successful saving, reset the flag:

  private save() {

Now replace the router's push function:

const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function(location: RawLocation) {
    if (blockRouteChange()) {
        if (confirm("There are unsaved changes, do you want to continue?")) {
            return, location) as any;
    return, location) as any;


Here is what I got:


This workaround works really well but I'm wondering whether there isn't a better possibility? Do you know how this can be achieved using a native solution? Maybe I just was not clever enough to type in the correct search terms into google 😅 Just let me know.

Found a typo?

As I am not a native English speaker, it is very likely that you will find an error. In this case, feel free to create a pull request here: . Also please open a PR for all other kind of errors.

Do not worry about merge conflicts. I will resolve them on my own.

Discussion (0)