Search code examples
javascriptvue.jsvuetify.js

vue.js force update input element not working


I have an input element that bind with v-model to a item value, I want to limit the user input to just type numeric value on range between 0 to 10, I was tried this thing before(add @input and check the input value to keep it in range)

my code is like this:

<v-text-field @input="checkItem" v-model="item"></v-text-field>

checkItem(val) {
      if(parseInt(val) < 1) {
        this.item = 1;
      } else if(parseInt(val) >10) {
        this.item = 10;
      }
    }

Problem after first time we type number out of range the function works great and keep it in range but when we type out of range number again the element didn't update because the new item value is the same as the old item value! to solve this I try to use forceUpdate and the $forceUpdate() not work!!!

for example

  • if user type anything between range number into input, because it's in range everything is ok;

  • but if user type 0 or any number outside of range, on the first time item value change to 1 if value was under 1 but if again type any negative value because the item value last time was changed to 1 when we set it to 1 again nothing happening on the view and the element value was not updated.

The main question is how to force vue to update this input field value?


Solution

  •   <div><input type="number" v-model="item"></input></div>
    </template>
    
    <script>
    export default {
      name: "ranges",
    
      data() {
        return {
          item: Number,
          error: String
        };
      },
    
      watch: {
        item(newVal, lastVal) {
          if (newVal > 10) this.item = 10
          if (newVal < 1) this.item = 1
        }
      }
    };
    </script>
    
    

    Here using the watcher you can do that validation