Categories
JavaScript Vue

Watch Input Change with Vue.js

Spread the love

We can watch for input value changes with Vue.js with the watch property.

Add a Watcher

To do this, we can add the watch property to our component. We can write the following to check watch for the inputted value of a model and do something to it as follows:

<template>
  <div id="app">
    <input v-model="value">
    <p>{{inputted}}</p>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      value: "",
      inputted: ""
    };
  },
  watch: {
    value(val) {
      this.inputted = `Inputted: ${val}`;
    }
  }
};
</script>

In the code above, we have the watch property that has the value method, which watches the value of the data state.

The v-model directive binds our inputted value to this.value, so this.value will always get the latest inputted value from the input.

The name of the state and the method name in watch have to match. Then we can get the val parameter and then set the this.inputted field as follows:

this.inputted = `Inputted: ${val}`;

Then we’ll see what we entered with Inputted: added before it.

Conclusion

We can add a watcher with the watch property. Then we can use that to update other values as the given value changes.

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 *