A
A
ArtJH2021-05-28 13:11:18
Vue.js
ArtJH, 2021-05-28 13:11:18

How in vue for input number to limit the number of input characters, for example, only 2 digits?

Found such solution but not on vue https://jsfiddle.net/DRSDavidSoft/zb4ft1qq/2/
But oninput doesn't work. I suspect due to vue

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-05-28
@ArtJH

make a directive that will adjust the number of characters:

const handlers = new Map();

function updateHandler(el, binding) {
  el.removeEventListener('input', handlers.get(el));

  const handler = () => {
    const value = el.value.replace(/\D/g, '').slice(0, binding.value);
    if (value !== el.value) {
      el.value = value;
      el.dispatchEvent(new Event('input'));
    }
  };
  handler();
  handlers.set(el, handler);

  el.addEventListener('input', handler);
}

Vue.directive('maxlen', {
  bind: updateHandler,
  update: updateHandler,
  unbind(el) {
    el.removeEventListener('input', handlers.get(el));
    handlers.delete(el);
  },
});

<input type="number" v-maxlen="2">

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question