A, watch

vm.$watch( expOrFn, callback, [options] )

  • Parameters:

    • {string | Function} expOrFn
    • {Function | Object} callback
    • {Object} [options]
      • {boolean} deep
      • {boolean} immediate
  • Return: {Function} unwatch

    From this we can see that Watch is an objectCopy the code

2, Need (immediate use)

Search box Searches for key values in real time

Watch: {fuzzyKey: {handler() {        this.searchCaseList()      },      immediate: true}}Copy the code

Wacth executes the handler method immediately if the fuzzyKey is changed, and then calls the handler function again. In addition, whenever I use immediate: true, I delete this.searchCaselist () from created. This avoids two calls. Instead, I use immediate: true, and the function is called when the page is initialized

Watch: {fuzzyKey: {handler() {this.searchcaselist ()}}},created(){this.searchCaseList()}Copy the code

There is also a case where watch is used instead of immediate: true or created

Watch: {fuzzyKey: {handler() {       
     this.searchCaseList()   
   }   
 }
}Copy the code

You can also try it out, and it turns out that this function is not called initially, because only function changes trigger handler functions

3. Requirements (deep usage)

Input box depth monitor

<div>
  <input type="text" v-model="person.name" />      <span> {{ person.fullname }} </span></div>
=====script======
data() {return {
  person: {        name: 'zhangsan',        lastname: 'lisi',        fullname: ' '      }     }
   }   
watch:{
 person:{        handler: function(newValue, oldValue) {        this.person.fullname = newValue.name + ' ' + this.person.lastname      },      // deep: true,      // immediate: true}}Copy the code



As you can see, the result is that the values of initialization and variation are not available

Add immediate: true



There are initialized values, but the values in the input field do not change

Add deep: true



It is possible to change in real time as the input value changes

Immediate: true indicates that the initial value is displayed. However, if you change the value in the input box, you must add deep: True, the span value changes in real time with the input field value.