The difference between Vue computed properties and listening properties

What computed can do, watch can do.

The functions that can be completed by watch may not be completed by computed. For example, watch can perform asynchronous operations.

Try to use computed to complete what can be done with computed, and use watch to complete what cannot be done with computed.

Computed properties implement data processing:

<div id="APP">
	姓:<input type="text" v-model="firstName"> <br/><br/>
	名:<input type="text" v-model="lastName"> <br/><br/>
	全名: <span>{
   
   {fullName}}</span>
</div>
const vm = new Vue({
	el: "#APP",
	data(){
		return {
			firstName: "张",
			lastName: "三"
		}
	},
	computed:{
		fullName(){
			return this.firstName + '-' + this.lastName;
		}
	},
});

 Summary : Calculated properties are suitable for use when multiple data affect one data, and are relatively simple to use. It is very convenient to implement the above functions with computed properties.

 The listener property implements data processing:

In order to implement the above functions for the listening attribute, a new variable needs to be created, because the data monitored by the listening attribute must exist. In addition, the listening attribute also needs to listen to the two variables firstName and lastName at the same time to realize this function.

<div id="APP">
	姓:<input type="text" v-model="firstName"> <br/><br/>
	名:<input type="text" v-model="lastName"> <br/><br/>
	全名: <span>{
   
   {fullName}}</span>
</div>
const vm = new Vue({
	el: "#APP",
	data(){
		return {
			firstName: "张",
			lastName: "三",
			fullName: "张-三"
		}
	},
	watch:{
		firstName(newValue){
			this.fullName = newValue + '-' + this.lastName;
		},
		lastName(newValue){
			this.fullName = this.firstName + '-' + newValue;
		}
	},
});

 Summary : The listening attribute is suitable for when one data affects multiple data, and it is relatively simple to use. It would be very troublesome to implement the above functions with the listener attribute.

Original author: Wu Xiaotang

Creation time: 2023.5.31

Guess you like

Origin blog.csdn.net/xiaowude_boke/article/details/130959793