3

I am pretty new to watch and trying to figure out why my watch isn't triggering when accessing it as an object. I saw this thread, but it isn't clear to me if my problem is the same. Following is my simplified example (full example got more properties and properties with array

<div id="app">
  <input type="text" v-model.lazy="userInfo.name"> {{userInfo.name}}
</div>

JS

new Vue({
  el: "#app",
  data: {
  userInfo: {
            name: ''
  }

  },
  methods: {

  },
  watch: {
    userInfo : {
            name(oldVal, newVal){
            console.log(oldVal +" " + newVal)
      },
    },
     deep: true
  }
})

Link to the JSFiddle

localhost
  • 822
  • 2
  • 20
  • 51
  • 2
    https://vuejs.org/v2/api/#watch – str Feb 28 '19 at 12:01
  • Possible duplicate of [Vue.js - How to properly watch for nested data](https://stackoverflow.com/questions/42133894/vue-js-how-to-properly-watch-for-nested-data) – Vucko Feb 28 '19 at 12:06
  • Change the watcher to something like this ` watch: { 'userInfo.name' : function(oldVal, newVal){ console.log(oldVal +" " + newVal); }, deep: true }` – Majid Feb 28 '19 at 12:19
  • thanks @Majid . It make good sense then docs. If u want Put it as answer and I will accept the answer. If possible, can u break down what it says in docs as it is hard to understand [vuejs.org/v2/api/#watch](watch) – localhost Feb 28 '19 at 12:22

2 Answers2

4

Change the watcher to something like this:

new Vue({
  el: "#app",
  data: {
    userInfo: {
      name: "null"
    }
  },
  methods: {},
  watch: {
    "userInfo.name": function(oldVal, newVal) {
      console.log(oldVal + " " + newVal);
    }
  }
});

Refer to the documentation for the same here. Check the last example.

tony19
  • 125,647
  • 18
  • 229
  • 307
Majid
  • 141
  • 2
  • 10
2

Here is a short example in your case:

new Vue({
  el: "#app",
  data: {
  userInfo: {
       name: 'null'
    }
  },
  computed: {
    name() {
      return this.userInfo.name;
    }
  },
  methods: {

  },
  watch: {
    name(newVal, oldVal) {
      alert(newVal);
      alert(oldVal);
    }
  },
})
robertkovacs
  • 435
  • 3
  • 14