4

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

0

2 Answers 2

3

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'));
}
Sign up to request clarification or add additional context in comments.

2 Comments

Unfortunately didn't work for me. Please check the codepen link in the updated post: enter " foo" as first name, press tab (see the trim in action), then start typing anything into last name and the trim will be undone
I've used the wrong event type, VueJS is listening to input event. I've tried the codepen example with input and it worked fine.
2

Refer this: https://stackoverflow.com/a/49602559/1364747

  1. Try the 'input' event
  2. Try the bind method and vnode if above doesn't work

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.