Skip to content
Advertisement

Vue: attaching @keyup/@input event to data property breaks form input

I’m trying to attach a simple character counter to an input element but the second I display it back to the user, the input breaks in that I’m unable to enter any additional characters in the input box.

JavaScript

To summarize the code above, I’m doing some basic cleansing on change, and am looking to trigger a character count on key up. What am I missing?

Advertisement

Answer

The characterCount update in the keyup handler is triggering a rerender of the entire component in order to render the new value of the characterCount string interpolation in the template. The rendering includes the <input>, whose value is bound to text. If text is an empty string or null, the <input> is effectively cleared on keyup.

To resolve the issue, use a local copy of the text prop that can be modified, and bind it to the <input>‘s v-model.

  1. Create a data property (named "value"), and a watcher on the text prop that copies text into value:

    JavaScript
  2. Use the new value property as the <input>‘s v-model:

    JavaScript
  3. Remove the keyup handler and the characterCount data property, and instead use a computed prop that returns the length of value:

    JavaScript

Edit Troubleshooting input changes

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement