I'm trying to implement a directive that will trim the value of an input on blur event:
import { DirectiveOptions } from "vue";
const Autotrim: DirectiveOptions = {
inserted(el) {
if(!(el instanceof HTMLInputElement) && !(el instanceof HTMLTextAreaElement)) {
throw 'Cannot apply v-autotrim directive to a non-input element!';
}
el.addEventListener('blur', () => {
if(el.value)
el.value = el.value.trim();
});
}
};
The input is updated, but the bound value in the model is not, and after any change somewhere else in the component it reverts back to an un-trimmed state.
What is the correct way to ensure the model is also updated?
EDIT Here's a codepen link to try: https://codepen.io/impworks/pen/mddMPyx
You need to trigger the input
event to let Vue know that value was changed.
Do this once you've detected that input value is different than current value (to avoid infinit recursion)
if (el.value && el.value !== el.value.trim()) {
el.value = el.value.trim();
el.dispatchEvent(new Event('input'));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With