Vue learning – Watch listener

What is the watch property in Vue and what does it do?

The watch property has a listener that listens for Vue data. The listener is essentially a function. To listen for changes to any data, use the data name as the method name.

The listener function takes two arguments:

The first parameter is the new value after the data change, and the second parameter is the old value before the data change.

Format of the listener in the Watch property

Listeners in the Watch property come in two formats:

  • Listeners in the form of methods

export default {
	data(){
	// Define some variables
	},
	watch: {// The property to listen for is placed in the watch property as a method
	property(){
			// A block of code in the listener is triggered when the listening property changes
			
			/* Code block */}}}Copy the code

Method listeners have disadvantages:

  • Disadvantage 1: cannot automatically trigger when entering the page;
  • Disadvantage 2: If the listener is listening on an object, the listener will not be triggered if the property inside the object changes.
  • Listeners in the form of objects

export default {
	data(){
	// Define some variables
	},
	watch: {// The property to listen for is placed in the watch property as a methodProperty1: {// The listener handler is triggered when the listening property changes
			handler(){},// set the deep attribute to true to enable deep listening;
			// If the value of any property of the object is changed, the handler function is triggered.
			// The default is false,
			deep:true.The immediate property controls whether the listener fires immediately upon entering the page
			// The default value is false and does not trigger
			immediate:true
		},
		
	// If you only listen for changes to a child property of the object;
	// Enclose the attribute names of the child attributes of this object in quotes
	'obj.property2': {handler(){},deep:true.immediate:true}}}Copy the code