gbalduzzi
gbalduzzi

Reputation: 10166

Vuejs input with v-model not updating when I sanitize the input on a watch handler

I'm using Vue 2.6 and I am encountering a weird problem when I sanitize an input.

I have a custom component for the actual input that is basically the following (I add some styling etc that is not relevant here):

<template>
  <input :name="name" :value="value" @input="(e) => onInput(e.target.value)" />
</template>

where onInput simply emits the input event, and both value and name are props.

I can use this component on my page:

<Field v-model="field" name="field" />

It works greatly on most cases.

The problem started because I need to remove all lowercase and whitecase characters from the input. So I created a watch handler on field:

onFieldChange(field) {
  this.field = field.replace(/[\sa-z]/gi, '')
}

Now, if I start typing something invalid like test and I inspect the Vue components, I can see that the field is correctly '', because all the invalid chars are stripped away, but I keep seeing test inside the input.

If I also add a valid char, such as T => testT then it renders correctly to only be T.

It's clear to me what is the problem origin: my Field component does not see any difference in its props ('value' remains the same, an empty string) and so it does not re-render. But I don't understand how I could solve it, do you have any ideas? Thanks

Upvotes: 0

Views: 934

Answers (1)

donMateo
donMateo

Reputation: 2394

Just modify your field value in nextTick.

onFieldChange(field) {
  this.$nextTick(()=>{
    this.field = this.field.replace(/[\sa-z]/gi, '')
  })
  // this.field = field.replace(/[\sa-z]/gi, '')
}

jsfiddle

Upvotes: 1

Related Questions