In depth understanding of Vue. js $watch method

  • 2021-08-05 08:12:50
  • OfStack

Bloggers have recently taught themselves vue. js in the official tutorial of vue. js. Bloggers have been dull since childhood, and they really don't understand many points in the tutorial. The $watch method to be mentioned next is one of the points that they don't understand. Let's first look at how the $watch method is interpreted in API of vue. js: an expression or computed property function to observe the change of Vue instance. The arguments obtained by the callback function are the new value and the old value. Expressions accept only supervised key paths. For more complex expressions, replace them with one function. Official example:


//  Key path 
vm.$watch('a.b.c', function (newVal, oldVal) {
 //  Do something 
})
//  Function 
vm.$watch(
 function () {
  return this.a + this.b
 },
 function (newVal, oldVal) {
  //  Do something 
 }
)

vm. $watch returns a cancel watch function to stop firing the callback:


var unwatch = vm.$watch('a', cb)
//  After that, cancel the observation 
unwatch()

The blogger looked at it carefully, but he was overwhelmed and didn't understand it. Fortunately, there are many great gods on the Internet. After checking, I finally understand the usage of this $watch method. To put it bluntly, $watch is to observe the change of 1 value. If the value 1 changes, then the statement in function will be executed. Needless to say, let's look directly at the code:

HTML:


<div id="watch">
    firstName:<input type="text" name="li" v-model="firstName">
    <br>
    lastName:<input type="text" name="fei" v-model="lastName">
    <p>fullName: {{fullName}}</p>
</div>

JS:


var vm = new Vue({
      el: '#watch',
      data: {
        firstName: 'a',
        lastName: 'fei',
        fullName: 'a fei'
      },
      watch: {
        firstName: function (val) {
          this.fullName = val + ' ' + this.lastName
        },
        lastName: function (val) {
          this.fullName = this.firstName + ' ' + val
        }
      }
})

In the code, we use wach method to monitor firstName and lastName, and we do double binding in input box. In this way, the value we input in firstName input box will change the value of firstName, and lastName can be obtained by the same token. Because of the change of value and the observation of watch, function code in watch will run, so fullName will change accordingly. In this way, the usage of $watch is clear. In the above example, $watch is similar to on-change in native js.

The above is the blogger's understanding of the $watch method. I hope it can help you understand this method. If there is anything wrong with the above, please point out it. Thank you.


Related articles: