@bg-dev/nuxt-naiveui
Version:
Unofficial Naive UI module for Nuxt
42 lines (41 loc) • 1.23 kB
JavaScript
import { ref, computed } from "#imports";
export function useNaiveForm(model = ref({})) {
const formRef = ref(null);
const pending = ref(false);
const rules = ref({});
const defaultModel = ref(JSON.parse(JSON.stringify(model.value)));
const apiErrors = ref(
{}
);
const edited = computed(
() => JSON.stringify(model.value) !== JSON.stringify(defaultModel.value)
);
function resetApiErrors() {
Object.keys(apiErrors.value).forEach(
(key) => apiErrors.value[key] = false
);
}
function onSubmit(callback) {
formRef.value?.validate((errors) => {
if (!errors) {
resetApiErrors();
pending.value = true;
callback().then(() => updateResetValue()).finally(() => {
pending.value = false;
formRef.value?.validate();
resetApiErrors();
});
}
}).catch(() => {
});
}
function reset() {
model.value = JSON.parse(JSON.stringify(defaultModel.value));
resetApiErrors();
formRef.value?.restoreValidation();
}
function updateResetValue() {
defaultModel.value = JSON.parse(JSON.stringify(model.value));
}
return { formRef, pending, rules, apiErrors, edited, reset, onSubmit, updateResetValue };
}