如果我的验证失败,如何停止输入事件?

时间:2019-03-04 07:10:40

标签: vue.js

我的输入很简单,只需要整数,但是如果我使用e.preventDefault()并返回到stop输入事件,则输入事件仍然有效。

input
    v-on:input="changeFraction"
    name="denominator"
    type="text"
    v-bind:value="fraction.denominator"

data() {
    return {
      fraction: {
        numerator: '',
        denominator: '',
      },
    };
  },
methods: {
    changeFraction(e) {
      const el = e.target;


      if (!/[0-9]/g.test(el.value)) {
          e.preventDefault();
          return null;
      }
        this.fraction[el.name] = el.value;

    },
  },

2 个答案:

答案 0 :(得分:1)

当输入无效时,只需使用computed进行验证,null进行@input事件。

例如:

<input type="text" v-model="fraction.numerator" @input="numeratorValid ? changeFraction : null"/>
computed: {
  numeratorValid () {
    return Number.isInteger(this.fraction.numerator)
  }
}

答案 1 :(得分:0)

<template>
  <div class = "fraction">

    <input
      @change = "changeFraction"
      name = "numerator"
      type = "number"
      v-model.number = "fraction.numerator" 
      />

    <input
      @change = "changeFraction"
      name = "denominator"
      type = "number"
      v-model.number = "fraction.denominator" 
    />

  </div>
</template>

<script>
  export default {
    name: 'FractionItem',
    data() {
      return {
        fraction: {
          numerator: '',
          denominator: '',
        },
      };
    },
    methods: {
      changeFraction(e) {
        const el = e.target;
        //need add plus before value, because writting letter in input change data value to string type
        if (!/[0-9]/g.test(+this.fraction[el.name])) {
          e.preventDefault();
        }

        this.$parent.changeFractionInput({
          id: this.id,
          [el.name]: +this.fraction[el.name],
          key: el.name,
        });
      },
    },
  }; 
</script>


<style lang = "scss" scoped></style>