I'm attempting to display a confirmation popup when the page reloads or the user navigates outside of my website in Vue.js.
I have already implemented the beforeRouteLeave
function in my component, but it only works when navigating to another page within my site, not when leaving the site or reloading the page. I also tried using the window.addEventListener
function, but the popup appears on all pages of my website.
I would like to display this confirmation message only on the page of this specific Vue component.
Here are some examples:
This code is inside the Vue Component:
beforeRouteLeave (to, from, next) {
const answer = window.confirm('Confirmation Message')
if (answer) {
next()
} else {
next(false)
}
},
This code is inside the Vue Component, but outside the export default
:
window.addEventListener('beforeunload', (event) => {
if (logic) {
event.returnValue = 'Are you sure you want to leave? Unsaved changes will be lost.'
}
})
How can this be achieved?