[Vuejs]-How do I bring up "Are you sure you want to leave page?" popup in vue.js router?

0👍

First you can assign a name for each of your routes objects in routes array inside your router or another field like requiredConfirmation or something like that, imagine that we have a routes like this :

routes : [
    {
    path : '/needconfirm',
    component : NeedConfirmToLeaveCom,
    name : 'needconfirm-route1'
  },
    {
    path : '/neednotconfirm',
    component : NeedNotConfirmToLeaveCom,
    name : 'normal-route1'
  },
]

then you can use router.beforeEach to set some conditions or some confirmations based on your Origin route and Destination route.
something like this :

router.beforeEach((to,from,next) => {
  if(from.name.startsWith("needconfirm-")) {
    if(window.confirm("Are you sure you want to leave the page?")) {
      next();
    }
  }else next();
});

UPDATE * :
if you want to use some custom components for your popup, you can use vuex to store your component’s logic and toggler and import that component in your App.Vue or other root/child components you wish. because you have access to your store management using $store right?

UPDATE ** :
and one other thing i want to mention, if you want to save some progress or state and because of that you want to get confirmation from user (progress will lost if they switch route), you should consider using Vuex to store your progress or state of your application and if you want more persisted solution you can use VuexPersisted store management which uses LocalStorage.

Vue router navigation guards document

Vuex Doc

0👍

You should use beforeunload event listener on the main component in that view.

MDN Reference

Depending on the browser, it will show the popup with default values populated.

This is how I use it in the created hook of the main component

 window.addEventListener("beforeunload", (e) => {
    e.preventDefault()
    // chrome requires returnValue to be set
    const message = "You have unsaved changes. Are you sure you wish to leave?"
    e.returnValue = message
    return message
})

Leave a comment