M
M
mrs4z2021-03-16 14:13:43
Vue.js
mrs4z, 2021-03-16 14:13:43

Vue Directive, v-model and input value, pass different values?

Good day to all!

There is a directive for working with numbers in INPUT, the main task is to divide 1,000,000, and work with fractions. Everything works great, but there is one thing. 1000000

-> INT

"1 000 000" -> String

model) to pass an unformatted number, that is, remove spaces, and so on .. Please tell me.

Of course, after each work in the component itself, you can parse, remove spaces, and so on, but this directive will be used quite a lot in the project, so I would like it to work automatically ..

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-05-09
@0xD34F Vue.js

Set to an unformatted value; pass the input event - so that the handler set by the directive v-modelupdates the data in the component; set the formatted value. To prevent recursive handling of input events, check isTrusted :

function updateValue(el) {
  el.value = el.value, из которого удалено всё, кроме цифр;
  el.dispatchEvent(new Event('input'));
  el.value = форматированное значение el.value;
}

function onInput(e) {
  if (e.isTrusted) {
    updateValue(e.target);
  }
}

Vue.directive('number', {
  bind(el) {
    el.addEventListener('input', onInput);
    updateValue(el);
  },
  update(el) {
    updateValue(el);
  },
  unbind(el) {
    el.removeEventListener('input', onInput);
  },
});

https://jsfiddle.net/Lsg6ct57/2/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question