简体   繁体   中英

Show popup when close tab in Vue Js

I'm trying to show a popup confermation when page reload or go outside my website in Vue js. I just have implemented the beforeRouteLeave function in my component, but this works only with when I go to another page in my site, not when I go outside or I reload the page. I just already try window.addEventListener function but the popup appears in all my website. I want to show up this confermation message only in the page of this Vue component

There are some example:

This is in the Vue Component:

beforeRouteLeave (to, from, next) {
  const answer = window.confirm('Confermation Message')
  if (answer) {
    next()
  } else {
    next(false)
  }
},

This is in the Vue Component, but outside the export default :

window.addEventListener('beforeunload', (event) => {
  if (logic) {
    event.returnValue = 'Sei sicuro di uscire? Le modifiche non salvate andranno perse'
  }
})

How can i do?

You could do

const confirmExit = () => window.confirm('Sei sicuro di uscire? Le modifiche non salvate andranno perse')

window.addEventListener('beforeunload', evt => {
  if (!confirmExit()) {
    evt.preventDefault();
    evt.returnValue = true;
  }
});

Then in your beforeRouteLeave method you can also check if (confirmExit()) instead of if (answer) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM