Vue.js, deep monitoring of watch

Because of Xiaobian's marriage and family affairs. I stopped updating for a long time. Today, Xiaobian came back again. Today, let's take you to learn about Vue Use of watch listening events in JS.

Usage of handler and immediate

<div>
     <h2>It's a fine day today{{info}}</h2>
   	 <button @click="isHot = !isHot">Point me</button>
</div>
 
new Vue({
  el: '#root',
  data: {
  	return{
	 	isHot: true
	}
  },
  computed: {
    info() {
      return this.isHot ? 'scorching hot' : 'pleasantly cool';
    },
  },
watch: {
    isHot: {
      immediate: true,  //The configuration item immediate represents immediate execution
      handler(newVal, oldVal) {
        console.log('isHot Has changed', newVal, oldVal);
      },
    },
  }
})

The effect shown in the above code is that when we click the button button, we change the value of isHot in data. We listen to the isHot attribute. When the value of isHot changes, handler will be called, and our console will output 'isHot has changed'. Handler receives two parameters newVal, oldVal, one is the new value and the other is the old value, Of course, these two values are not necessary. We can receive them when we need them. It doesn't matter if we don't receive them.

Of course, one of the characteristics of watch here is that it will not be executed at the time of initial binding, and the listening calculation will not be executed until isHot changes. What should we do if we want to make the handler execute the change at the beginning of the initial binding? The above configuration item adds immediate, which means that the handler will execute once immediately. What does it mean? It means that if the isHot value does not change, the handler will not call, but with immediate, the handler will execute once as soon as we enter the page.

Take the above code as an example. If immediate is false and isHot has not changed, the console will not output. When we click the button, the console outputs "isHot has changed", false and true, but when immediate is true and the button is not clicked, The console outputs' isHot has changed ', true and undefined.

deep attribute

Today's key point is that there is another important attribute deep in watch, which represents whether to monitor deeply. The default is false. What does it mean? Go directly to the code.

<div>
     <h2>It's a fine day today{{info}}</h2>
   	 <button @click="isHot = !isHot">Point me</button>
</div>
 
new Vue({
  el: '#root',
  data: {
    return{
    	numbers:{
    		a:1,
    		b:2,
    		......
    	}
    }
  },
  watch:{
      numbers:{
          deep:true, // Deep monitoring, which can monitor more than one level
          handler(){
              console.log('numbers Changed')
          }
      }
  }
})

Now we have such a requirement, that is, how to write when we want to monitor the changes of attributes in numbers. Many small partners will write this:

watch:{
      numbers:{
          handler(){
              console.log('numbers Changed')
          }
      }
  }

I can tell you clearly. It's wrong to write poems like this. I don't believe you can modify numbers on the console A, the console will not output console Log ('numbers changed '), why is this wrong? Because Vue cannot detect the addition or deletion of object attributes. Because Vue will perform getter/setter conversion on the attribute when initializing the instance, the attribute must exist on the data object to make Vue convert it and make it responsive.
By default, the handler only listens to the change of the reference of the attribute obj. It only listens to obj when we assign a value to it. For example, we reassign obj in the mounted event hook function:

mounted: {
  this.obj = {
    a: 456
  }
}
If it is written in this way, it can be monitored numbers Changeable

Some students said, Xiao Bian is stupid. You can write this:

watch:{
      'numbers.a':{
          handler(){
              console.log('numbers Changed')
          }
      },
      // If you want to monitor b:
      'numbers.b':{
          handler(){
              console.log('numbers Changed')
          }
      },
      ...........
  }

Dissatisfied with what you said, it's OK to write like this, but Xiaobian suggested you not to write like this. Why? What if I have 10000 attributes below? Do you want to write 10000, too? Unless you only listen to one or two attributes under the numbers object, this method is OK. But the effect we want now is that this method is not feasible as long as the value of an attribute under the numbers object changes.
At this time, we only need to add a configuration item deep in the numbers object to listen to numbers:

watch:{
      numbers:{
   		deep:true,
        handler(){
            console.log('numbers Changed')
        }
      }
  }

Deep means deep observation. The listener will traverse down layer by layer and add this listener to all the attributes of the object. In this way, as long as the value of any attribute in our numbers object changes, it will be monitored.

That's all for today's sharing. I hope you can learn from it. I also hope you can put forward more valuable opinions. Thank you for your reference.

Keywords: Javascript Front-end Vue Vue.js Interview

Added by ttroutmpr on Mon, 21 Feb 2022 16:16:01 +0200