Home > Enterprise >  Is that possible to pass v-model ref to event handler
Is that possible to pass v-model ref to event handler

Time:03-23

I want to make a universal handler for input event and I need somehow to change v-model value in it. I tried this:

function validateInput(event) {
  let input = event.target.value;
  input = parseInt(input);
  if(isNaN(input)) {
    event.target.value = '';
  } else {
    event.target.value = input;
  }
}

<input @input="validateInput($event)"
  v-model="inputRef">

But inputRef doesn't react on event.target.value changes.

CodePudding user response:

As Boussadjar mentioned, modifying event.target.value is no option.

just return the value from the event handler:

function onlyNumbersFilter(event) {
  let input = event.target.value;
  input = parseInt(input);

  return isNaN(input) ? '' : input;
}

and use it:

<input @input="inputRef = onlyNumbersFilter($event)" :value="inputRef">

Or if you want to stick with v-model:

// setup
import { computed, ref } from 'vue'

// val is not DOM Event but value itself unwrapped from $event.target.value
function onlyNumbersFilter(val) {
  const n = parseInt(val);

  return isNaN(n) ? '' : val;
}

const filteredModel = function(valueRef, filterFn) {
  return computed({
    get() { return valueRef.value }
    set(newVal) { valueRef.value = filterFn(newVal)) }
  })
}

const input1Value = ref('')
const input1Model = filteredModel(input1Value, onlyNumbersFilter)

return {
  input1Model
}

and usage:

<input v-model="input1Model">

CodePudding user response:

In this case you should use value instead of v-model since v-model is the equivalent of @input ant value :

function validateInput(event) {
  let input = event.target.value;
  input = parseInt(input);
  if(isNaN(input)) {
    inputRef.value = '';
  } else {
   inputRef.value = input;
  }
}

<input @input="validateInput($event)"
  :value="inputRef">
  • Related