Listen for a property

If you only listen for a property of an object, you can listen for the property as a string. The property name)

<template>
  <div class="watch">
    <button @click="changeName">Modify the obj. Name</button>
    <input type="text" v-model="obj.name" />
    <button @click="changeSex">Modify the obj. Sex</button>
    <input type="text" v-model="obj.sex" />
  </div>
</template>
Copy the code
<script>
export default {
  data() {
    return {
      obj: {
        name: "Warmth".sex: "Male",}}; },watch: {
    "obj.name": {
      handler(newValue, oldValue) {
        console.log("Obj's name has changed.");
        console.log('newValue: ' + newValue);
        console.log('oldValue: '+ oldValue); }},},methods: {
    changeName() {
      this.obj.name += "1";
    },
    changeSex() {
      this.obj.sex += "1"; ,}}}; </script>Copy the code

It’s important to note that handler is a fixed notation, you can’t use anything else.

The depth of the listening

  • When it is necessary to monitor the changes of an object, the ordinary watch method cannot monitor the changes of the internal properties of the object. In this case, the deep property is needed to monitor the object deeply
  • Modify the code in Watch, other codes are the same as above
watch: {
    obj: {
      handler(newValue, oldValue) {
        console.log("Obj has changed.");
      },
      deep: true.immediate: true,}},Copy the code

Immediate indicates whether the handler is executed when the watch is first bound. If the value is true, the handler method is executed immediately when the watch is declared. If the value is false, it is the same as the watch. Handler is executed only when the data changes. The handler function is executed immediately after the GIF image is refreshed because the immediate attribute is set to true