简体   繁体   中英

How to display an error message on invalid input?

I have the following simple Vue 3 app that divides a dividend by a divisor, displaying the quotient and remainder. It allows the user to perform different calculations by modifying any of the four numbers:

<div id="app">
<input type="text" v-model.number="dividend"> divided by <input type="text" v-model.number="divisor">
is
<input type="text" v-model.number="quotient"> remainder <input type="text" v-model.number="remainder">
</div>
<script src="https://unpkg.com/vue@next"></script>
<script>
Vue.createApp({
  data() { return {
    dividend: 100,
    divisor: 7
  }},
  computed: {
      quotient: {
        get: function() { return Math.floor(this.dividend / this.divisor); },
        set: function(v) { this.dividend = v * this.divisor + this.remainder; }
      },
      remainder: {
        get: function() { return this.dividend % this.divisor; },
        set: function(v) { this.dividend = this.quotient * this.divisor + v; }
      }
    }
}).mount("#app");
</script>

This works fine, unless you try to enter a remainder that's >= the divisor. In that case, the remainder is adjusted - eg if the divisor is 7 and you try to enter remainder 9, instead 2 appears as the remainder and the quotient is increased by 1. I think this is non-intuitive - the remainder should instead reflect what has been typed in. So, I changed the remainder setter to:

set: function(v) { if (v < this.divisor) this.dividend = this.quotient * this.divisor + v; }

Now, if you enter a remainder that's too large, the calculation does not update until you either fix the remainder or change one of the other values.

But, in the case where the remainder is too large and the calculation is not updating, I would like to display an error message to the user. How can I implement this?

watch can do.

Add a new prop for control the state and you can check the input is valid.

<div v-if="!isValidInput">Your alert messages.</div>

data() { 
 return {
    dividend: 100,
    divisor: 7,
    isValidInput: true,
  }},
watch: {
    'dividend': function(val){
      if (your_conditions) {
        this.isValidInput = false;
      }
    },
    'divisor': function(val){
      if (your_conditions) {
        this.isValidInput = false;
      }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM