Reputation: 2818
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
Upvotes: 4
Views: 6845
Reputation: 4223
Refer this: https://stackoverflow.com/a/49602559/1364747
Upvotes: 2
Reputation: 992
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'));
}
Upvotes: 3