Prevent Navigation Away

We can use the native beforeunload event to detect when a user is about to navigate away or refresh the page:

// Use `beforeMount` to avoid running during SSR
onBeforeMount(() => {
// We use the native `beforeunload` event
window.addEventListener("beforeunload", preventNav);
});
// Make sure to always clean up after yourself!
onBeforeUnmount(() => {
window.removeEventListener("beforeunload", preventNav);
});

The method to actually block the navigation uses preventDefault:

const blockNavigation = ref(false);
const preventNav = event => {
if (!blockNavigation.value) return;
event.preventDefault();
// Chrome requires returnValue to be set
event.returnValue = "";
};

Here's the full example:

<script setup>
import { ref, onBeforeMount, onBeforeUnmount } from 'vue';
// Method to block navigation
const blockNavigation = ref(false);
const preventNav = event => {
if (!blockNavigation.value) return;
event.preventDefault();
// Chrome requires returnValue to be set
event.returnValue = "";
};
// Use `beforeMount` to avoid running during SSR
onBeforeMount(() => {
// We use the native `beforeunload` event
window.addEventListener("beforeunload", preventNav);
});
// Make sure to always clean up after yourself!
onBeforeUnmount(() => {
window.removeEventListener("beforeunload", preventNav);
});
</script>