📜  vue watch handler - Javascript (1)

📅  最后修改于: 2023-12-03 15:35:38.370000             🧑  作者: Mango

Vue.js Watch Handler

In Vue.js, watch is a powerful feature that allows developers to watch for changes to data properties and perform actions based on those changes. A watch handler is a function that gets executed every time the data being watched changes.

Syntax
watch: {
  'propertyName': function(newValue, oldValue) {
    // Handle the change
  }
}
  • propertyName: The name of the property being watched.
  • newValue: The new value of the property.
  • oldValue: The old value of the property before the change.
Usage

With watch, developers can perform actions based on changes to a specific property. For example, if you want to perform a calculation every time the price property changes, you can write the following watch handler:

data() {
  return {
    price: 10.0,
    tax: 0.16,
    total: 0.0
  };
},
watch: {
  'price': function(newValue, oldValue) {
    this.total = newValue + (newValue * this.tax);
  }
}

In this example, we're watching the price property, and every time it changes, we're updating the total property based on the new price and the tax rate.

Tips
  • You can watch for changes to multiple properties by adding multiple watch handlers to your component.
  • When using watch, you need to make sure that you're not creating an infinite loop that causes the function to run indefinitely.
  • You can use the immediate option to run the watch handler immediately when the component mounts, even if the data hasn't changed yet.
watch: {
  'propertyName': {
    immediate: true,
    handler: function(newValue, oldValue) {
      // Handle the change
    }
  }
}