-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFormNavigationGuard.vue
More file actions
58 lines (47 loc) · 1.42 KB
/
FormNavigationGuard.vue
File metadata and controls
58 lines (47 loc) · 1.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<script setup lang="ts">
import { useConfirm } from '@/lib/primevue';
import { onBeforeRouteLeave, useRouter } from 'vue-router';
import { useIsFormDirty } from 'vee-validate';
import { ref } from 'vue';
import { FormAutosave } from '@/components/form';
import type { Ref } from 'vue';
// Props
const { autoSaveRef = null, callback = () => {} } = defineProps<{
autoSaveRef?: InstanceType<typeof FormAutosave> | null;
callback?: (...args: any[]) => any;
}>();
// State
const isAccepted: Ref<boolean> = ref(false);
const isDirty = useIsFormDirty();
const isOpen: Ref<boolean> = ref(false);
// Actions
const confirm = useConfirm();
const router = useRouter();
onBeforeRouteLeave(async (to) => {
autoSaveRef?.stopAutoSave();
// Skip navigation guard if already accepted
if (isAccepted.value) return true;
if (isDirty.value && !isOpen.value) {
isOpen.value = true;
confirm.require({
message: 'Are you sure you want to leave this page? Any unsaved changes will be lost.',
header: 'Leave this page?',
acceptLabel: 'Leave',
acceptClass: 'p-button-danger',
rejectLabel: 'Cancel',
rejectProps: { outlined: true },
accept: async () => {
isAccepted.value = true;
await callback();
router.replace(to);
},
reject: () => (isOpen.value = false)
});
return false;
} else {
await callback();
}
return true;
});
</script>
<template><div /></template>