How to watch the change of an element value with Vue.js?

Sometimes, we want to watch the change of an element value with Vue.js.

In this article, we’ll look at how to watch the change of an element value with Vue.js.

How to watch the change of an element value with Vue.js?

To watch the change of an element value with Vue.js, we can add a watcher.

For instance, we write

<script>
//...
export default {
  //...
  watch: {
    myValue(val, oldVal) {
      if (val < 50) {
        this.message = "value too low!";
      } else {
        this.message = "value is ok";
      }
    },
  },
  //...
};
</script>

to watch the myValue reactive property for changes.

We get its latest value from val and its previous value from oldVal.

And then we can do whatever we want in the watcher method according to the values.

Conclusion

To watch the change of an element value with Vue.js, we can add a watcher.