by Sai gowtham

How to Properly watch nested data in Vue.js

This example shows you, how to watch nested data structures in Vue.js

<template>
  <div id="app">
    <input v-model="items.a">
    <p>{{items.a}}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      items: {
        a: 1,
        b: 2,
        c: 3
      }
    };
  },
  watch: {
    'items.a': function(newval, oldVal) {      console.log("new: %s, old: %s", newval, oldVal);
    }
  }
};
</script>

Now, if we type something new in input element, vue watches the items.a property and runs the function.

The watcher function shows us new value and old value(previous value) passed to that property.

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course