preface

The best time to plant a tree was ten years ago, followed by now. It doesn’t matter who says it.

Clear requirements

When making forms, we often encounter various input fields. For example, when designing the number of fields to be filled in, we require the input of a positive integer.

Common implementation

If it is just an individual input field, then we can detect the input keyUp event and operate on the keyUp event within that event

    <input type="text" v-model="value" 
    @keyup="value = value.length === 1 ? value.replace(/[^1-9]/g, '') : value.replace(/\D/g, '')" />
Copy the code

If there are lots of requirements for positive integers, it’s not fun

High-level implementation

The final result

Come on!

First, the final result:

<input type="text" v-model="value" v-Int/>
Copy the code

Confirmed the eyes, as simple as adding instructions v-int can be achieved, is not the feeling of heart?

implementation

  1. Create a new JS file with the following code

conclusion

If you use their own small skills are customized to maintain, that is not beautiful.

correction

After some time, the input value is changed, but the vue still displays the old value. This is a serious bug. So I spent the morning trying to figure out why… Find a solution:

import Vue from 'vue'
exportDefault () => {// Only positive integers can be entered for el-input. Vue.directive('Int', {
    bind: function (el) {
      const input = el.getElementsByTagName('input')[0]
      input.onkeyup = function (e) {
        if (input.value.length === 1) {
          input.value = input.value.replace(/[^1-9]/g, ' ')}else {
          input.value = input.value.replace(/[^\d]/g, ' ')
        }
        trigger(input, 'input')
      }
      input.onblur = function (e) {
        if (input.value.length === 1) {
          input.value = input.value.replace(/[^1-9]/g, ' ')}else {
          input.value = input.value.replace(/[^\d]/g, ' ')
        }
        trigger(input, 'input')}}}} / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Fn: trigger * * Intro: reference https://github.com/vuejs/Discussion/issues/157#issuecomment-273301588
  ** Author: zyx
*********************************/
const trigger = (el, type) => {
  const e = document.createEvent('HTMLEvents')
  e.initEvent(type.true.true)
  el.dispatchEvent(e)
}

Copy the code

The bug has been fixed by now. The solution to this bug can be found at github.com/vuejs/Discu…