Files
wordpress-theme-aksrt/assets/admin/src/composables/useDirtyState.js
T

51 lines
1.1 KiB
JavaScript

import { ref, watch, computed } from 'vue'
/**
* useDirtyState — tracks whether a form has unsaved changes.
*
* Usage:
* const { isDirty, markDirty, markClean, confirmLeave } = useDirtyState()
*
* Call markDirty() whenever form data changes from its initial state.
* Call markClean() after a successful save.
* confirmLeave() returns a boolean — false means the user cancelled navigation.
*/
export function useDirtyState() {
const dirty = ref(false)
const saveCount = ref(0)
function markDirty() {
dirty.value = true
}
function markClean() {
dirty.value = false
saveCount.value++
}
/** Reset dirty without incrementing save count (e.g. on initial load) */
function reset() {
dirty.value = false
}
/**
* Confirm navigation away from dirty form.
* Returns true if safe to leave, false if user cancelled.
*/
function confirmLeave() {
if (!dirty.value) return true
return window.confirm('您有未保存的更改,确定要离开此页面吗?')
}
const isDirty = computed(() => dirty.value)
return {
isDirty,
markDirty,
markClean,
reset,
confirmLeave,
saveCount,
}
}