Input/Textarea nullify modifier
Description
Most of the time when I work with forms, I have some sort of state object like so:
const state = ref({
name: '',
email: '',
company: null,
title: null,
});
When a user changes the value in the input, the value will never be null again (even if they delete their input).
Currently, the solution is doing null coercion in e.g. a useFetch function:
// code snippet only for illustration
const { data } = await useFetch('/api/some/endpoint', {
method: 'POST',
body: {
name: state.value.name,
email: state.value.email,
company: state.value.company ?? null,
title: state.value.title ?? null,
},
});
This requires spreading and/or overriding values independently. Say you have some kind of dashboard application with many forms (my case), then you have to do this for every form that has "optional" inputs.
What you actually want is:
const { data } = await useFetch('/api/some/endpoint', {
method: 'POST',
body: state,
});
Where the input returns null if it contains an empty string.
This can be done by adding a model modifier:
<UInput v-model.nullify="state.company" />
Just like trim and number trims the value or coerces to a number respectively.
Additional context
This PR depends on allowing null as initial value as implemented in (#2275)