Vue.js Watch Property

Vue.js Watch Property

The watcher in Vue.js listens to the component data and executes when it finds changes in any property. It is an essential feature of the Vue.js framework that allows us to spy on a Vue object property, and execute a function when the computed property value changes.

Example: This example explains how we can use the watch property in the Vue.js application.

Index.Html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>vue.js watcher</title>
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
  </head>
  <body>
<div id="app">
  Course: <input type="text" v-model="searchQuery">
  <p v-if="isSearching">Searching...</p>
  <div v-else>
    <ol>
      <li v-for="result in results">{{ result }}</li>
    </ol>
  </div>
</div>
  </body>
</html>
Main.js
import Vue from 'vue'
import App from './App'
import router from './router'
Vue.config.productionTip = false
new Vue({
            el: '#app',
  data: {
    searchQuery: '',
    results: [],
    isSearching: false
  },
  methods: {
  },
  computed: {
  },
  watch: {
            searchQuery: function(query) {
      this.isSearching = true;
      var vm = this;
      setTimeout(function() {
            vm.results = ['Java', 'JavaScript', 'Python', 'MySQL'];
vm.isSearching = false;
      }, 250);
    }
  }
});

Output: After executing this code, we will get the output, as shown below:

Vue.js Watch Property

When we enter the course name in a textbox, it takes few seconds to show the result of its hidden data, as shown below:

Vue.js Watch Property

When we enter the values inside the textbox, whatever it gets changes, the “Watch Property” is responsible for updating the textbox. Here, we don’t have to specially define any events and wait for it to change and do the extra work of validating. Watch property is responsible for updating the textbox with the calculation performed in the respective functions.