Inertia.js does not have a built-in equivalent to Vue Router's beforeRouteLeave navigation guard. However, you can achieve similar functionality by using Inertia's event system, specifically by listening to the navigate event.
Here's how you can set up a guard to check for unsaved changes before navigating away from a route in an Inertia.js/Vue application:
-
Setup a reactive state for tracking changes: You'll need a way to track whether there have been changes in your component that haven't been saved.
-
Listen for Inertia's
navigateevent: This event is triggered when a navigation is initiated. -
Conditionally cancel navigation: If there are unsaved changes, you can show a confirmation dialog. Based on the user's response, you can either proceed with or cancel the navigation.
Here's an example implementation:
<template>
<div>
<input v-model="formData.name" @input="changesMade = true" />
<!-- Your form and other inputs -->
</div>
</template>
<script>
import { Inertia } from '@inertiajs/inertia'
export default {
data() {
return {
formData: {
name: '',
},
changesMade: false
}
},
mounted() {
window.addEventListener('beforeunload', this.beforeWindowUnload)
Inertia.on('navigate', this.handleBeforeRouteLeave)
},
beforeUnmount() {
window.removeEventListener('beforeunload', this.beforeWindowUnload)
Inertia.off('navigate', this.handleBeforeRouteLeave)
},
methods: {
beforeWindowUnload(event) {
if (this.changesMade) {
event.preventDefault()
event.returnValue = ''
}
},
handleBeforeRouteLeave(event) {
if (this.changesMade && !confirm('You have unsaved changes. Are you sure you want to leave?')) {
event.preventDefault()
}
}
}
}
</script>
Explanation:
-
Data Properties:
-
formData: Holds the form data. -
changesMade: A boolean to track if changes have been made.
-
-
Lifecycle Hooks:
-
mounted: Adds event listeners when the component is mounted. -
beforeUnmount: Removes event listeners when the component is about to unmount.
-
-
Methods:
-
beforeWindowUnload: Handles the browser's beforeunload event, which is triggered when the page is about to be unloaded (e.g., closing a tab). -
handleBeforeRouteLeave: This method is triggered by Inertia'snavigateevent. It checks if there are unsaved changes and shows a confirmation dialog.
-
This setup helps ensure that users are prompted when they attempt to navigate away with unsaved changes, similar to the beforeRouteLeave guard in Vue Router.