Detailed explanation of watch instance in vuejs (listener)

Time:2020-11-9

Recently, I just finished the celebration for more than a year, and my mind was always in the plot. Then I felt that in vuejs, watch was the supervision institute, a real spy agency. In Vue, watch is called a listener. It observes the change of every data in Vue instance at any time, and responds when the data changes.

Let’s take a look at the operation of the supervision institute through the following example code:

new Vue({
  el:"#app",
  data(){
    reutrn {
      candy:""
    }
  },
  //The legendary monitoring house start
  watch:{
    candy:{
      handler(newVal,oldVal){
      },
      immediate: true,
      deep:true
    }
  }
  //End of Supervision Institute in transmission
})
/***
Monitor the change of candy data in watch,
Two parameters are passed in handler:
Newval - > is the changed data
Oldval - > is the data before the change
***/

According to the plot analysis of Qing Nian Nian, the court of supervision is monitoring candy. Once candy breaks up, it will perform the operation in handler. It seems that newval and oldval are provided to the staff of the supervision yuan to determine what punishment to impose according to the circumstances if candy is an internal struggle or treason.

What do “immediate” and “deep” mean in the code?

Immediate and deep are like instructions given to Chen Pingping by Emperor Qing:

If immediate is true, it tells the supervision yuan that no matter whether candy has defected or not, he will be punished first!

Deep is true to tell the supervision institute to check in depth to see if anyone has contacted this person, and then something happened again!

When I wrote this article, I was also discussing watch and updated with my friends. Updated also makes corresponding changes when the data changes, but it would be too much to say that updated is the supervision institute! Updated cannot specify the monitoring data. As long as the data changes, it will point to the method in the updated. No matter who changes, it will be implemented. How can it match such a powerful spy agency of the Chinese Academy of supervision! Hee hee!

summary

The above is a detailed explanation of the watch instance in vuejs introduced by Xiaobian. I hope it will help you!