Chris Camaratta
Chris Camaratta

Reputation: 2779

How does one make arrow keys on number inputs lazy in Vue?

Vue supports lazy binding to models with the lazy modifier, e.g.

<input v-model.lazy="value" />

Now the model isn't updated until the input loses focus. However, if I change the type to Number and use the arrow keys to set the value, the model updates while the input has focus:

<input type="number" v-model.lazy="value" />

Is there an (easy) way to delay binding until after focus is lost?

Upvotes: 0

Views: 823

Answers (1)

Muge
Muge

Reputation: 374

v-model is synonymous for :value + @change. Assuming the arrows on input trigger a focus event, you can try replacing v-model with :value and @blur pair. Might not work if .lazy modifier already does this.

<input type="number" :value="value" @blur="value = $event.target.value" />

Another alternative is to "debounce" the change event with a set time so the value doesn't update while the user is changing the value.

Edit: debounce example using npm package

After installing and importing the debounce package, you need to create/assign the "debounced" version of the method (should define it in methods) to a method name under created (can be a different method name but should match what you put in @blur listener.

<input type="number" :value="value" @blur="updateValueOnBlur" />

created() {
  this.updateValueOnBlur = debounce(this.updateValueOnBlur, 500);
},
methods: {
  updateValueOnBlur(e) {
    this.value = e.target.value;
  },
}

Upvotes: 1

Related Questions