[Vuejs]-VueJs Watch per key of a model

0👍

You can watch a computed value that return the specific field that you want to watch.

Vue.config.devtools = false;
Vue.config.productionTip = false;

var app = new Vue({
  el: '#app',
  data: {
    form: {
      name : '',
      lastname: ''
    }
  },
  computed: {
    formName() {
      return this.form.name;
    }
  },
  watch: {
    formName() {
      console.log("Name has changed")
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  Name : 
  <input v-model="form.name" />
  Lastname : 
  <input v-model="form.lastname" />
</div>

0👍

You can explicitly watch the required key only.

new Vue({
  el: '#app',

  data: {
    search: {
      name: { placeholder: 'search name', value: '' },
      age: { placeholder: 'search age', value: '' },
      country: { placeholder: 'search country', value: '' }
    }
  },

  watch:{
    'search.name.value': { // Explicitly watch the required key.
        handler(){
            console.log('name changed...')
        }
    }
  }
})
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">

   <form>
    <input
      v-for="(value, key, i) in search"
      :key="i"
      v-model="search[key].value"
      type="search"
      id="filterInput"
      :placeholder="value.placeholder"
    /> 
   </form>
 
 </div>

So, here watch’s handler is called only when the name is searched & does not get called when age or country is searched.

Leave a comment