In Vue, watch is used to respond to data changes. The sample code is as follows:

The first way

<input type="text" v-model="userName"/> { userName (newName, oldName) { console.log(newName) } }Copy the code

One disadvantage of the first approach is that the listener is not executed when the value is first bound, but only when the value changes.

If we want to execute this listener on the first binding, we need to set immediate to true. For example, when the parent component transmits values dynamically to its child components and the child component obtains the default value from the parent component for the first time, the function needs to be executed. In this case, set immediate to true.

The second way

watch: {
	userName: {
		handler (newName, oldName) {
			console.log(newName)
		},
		immediate: true
	}
}
Copy the code

Immediate Indicates whether the handler is executed when the watch is first bound. If the value is true, the handler method is executed immediately when the watch is declared. If the value is false, the handler is executed only when data changes.

When it is necessary to monitor the change of an object, the ordinary watch method cannot monitor the change of the internal properties of the object. Only the data in data can monitor the change. In this case, the deep property is needed to monitor the object deeply.

The third way

<input type="text" v-model=" cityname.name "/> data (){return {cityName: {name:' Beijing ', location: 'China'}}}, watch: { cityName: { handler(newName, oldName) { console.log(newName) }, immediate: true, deep: true } }Copy the code

Note: When monitoring as an object, newVal == oldVal

All attributes of cityName will be listener. If there are many attributes, handler will be executed for each attribute value change. If you only need to listen for an attribute value in an object, you can optimize the following:

watch: {
	'cityName.name': {
		handler(newName, oldName) {
			console.log(newName)
		},
		immediate: true,
		deep: true
	}
}
Copy the code

note

  • Array changes do not require deep listening;
  • Do not use the arrow function in watch, because the arrow function this refers to the current scope.

Expand on the use and differences between Computed and Watch in VUE

Computed

This property can be associated with multiple objects that are evaluated in real time. This property can be triggered whenever one of these objects changes, so it will only be re-rendered if the data changes again, otherwise the data will be fetched directly from the cache.

For example, when we want the background color of a DIV element to match the text color, we can use computed properties. In this case computed fires only when the rendering is first done and the text color changes. Other cases read directly from the cache.

Watch

Customizing the watch can be helpful when you need to perform asynchronous or high-performance operations in response to data changes.