What is the watch option handler in Vue

take a look at Vue"s API about watch options here, the code in the official tutorial:

var vm = new Vue({
  data: {
    a: 1,
    b: 2,
    c: 3,
    d: 4,
    e: {
      f: {
        g: 5
      }
    }
  },
  watch: {
    a: function (val, oldVal) {
      console.log("new: %s, old: %s", val, oldVal)
    },
    // 
    b: "someMethod",
    //  watcher
    c: {
      handler: function (val, oldVal) { /* ... */ },
      deep: true
    },
    // 
    d: {
      handler: function (val, oldVal) { /* ... */ },
      immediate: true
    },
    e: [
      function handle1 (val, oldVal) { /* ... */ },
      function handle2 (val, oldVal) { /* ... */ }
    ],
    // watch vm.e.f"s value: {g: 5}
    "e.f": function (val, oldVal) { /* ... */ }
  }
})
vm.a = 2 // => new: 2, old: 1
Where does the handler method appear in the

example come from? It seems that you can"t replace

with another name.
Nov.16,2021

this is the rule of vue. When the value of your watch changes, the handler, will be triggered. This is what vue does internally for you.


you can refer to the section in state.js in the source code. When the class of Vue initializes and establishes data binding, it will determine what to listen for from the parameters passed by the user, and what will be used as the processing function after listening to data changes. Because you pass an object after the variable, this object is the corresponding handler, function in the createWatcher function parameters. The first step of logic is to determine whether it is an object. If it is an object, take the handler parameter inside it as the handler for listening events, so this property must be written like this.

function createWatcher (
  vm: Component,
  expOrFn: string | Function,
  handler: any,
  options?: Object
) {
  if (isPlainObject(handler)) {
    options = handler
    handler = handler.handler
  }
  if (typeof handler === 'string') {
    handler = vm[handler]
  }
  return vm.$watch(expOrFn, handler, options)
}

  • handle is the method that needs to be executed in your watch
  • deep: is the depth of the data you need to listen to, which is generally used to listen for changes in an attribute in an object
  • immediate: specifying immediate: true in the option parameter will immediately trigger a callback with the current value of the expression:
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b3c46b-2c30b.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b3c46b-2c30b.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?