In my Vue 3 application, I have implemented a simple calculator that divides a dividend by a divisor and displays the quotient and remainder. Users can adjust any of the four numbers to perform different calculations.
<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) { if (v < this.divisor) this.dividend = this.quotient * this.divisor + v; }
}
}
}).mount("#app");
</script>
However, when users input a remainder greater than or equal to the divisor, the remainder is automatically adjusted. For example, if they enter 9 as the remainder when the divisor is 7, it will be displayed as 2 with the quotient increasing by 1. This may seem counterintuitive, so I modified the setter for the remainder:
set: function(v) { if (v < this.divisor) this.dividend = this.quotient * this.divisor + v; }
Now, if an invalid remainder is entered, the calculation does not update until the user corrects it or modifies another value. However, in such cases, I would like to show an error message to guide the user. How can I go about implementing this feature?