Categories
Vue Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *