Vue 计算属性与侦听属性的区别

computed 能完成的功能,watch 都可以完成。

watch 能完成的功能,computed 不一定能完成,例如:watch 可以进行异步操作。

能用 computed 完成的尽量用 computed 去完成,不能用 computed 完成的再用 watch 去完成。

计算属性实现数据处理:

<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;
		}
	},
});

 总结:计算属性适合在多个数据影响一个数据时,使用比较简单。以上功能用计算属性实现就非常方便。

 侦听属性实现数据处理:

侦听属性想要实现以上功能,还需要再新建一个变量,因为侦听属性监听的数据必须存在。另外侦听属性还需要同时监听 firstName 和 lastName 这两个变量才能实现该功能。

<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;
		}
	},
});

 总结:侦听属性适合在一个数据影响多个数据时,使用比较简单。以上功能用侦听属性实现就会非常麻烦。

原创作者:吴小糖

创作时间:2023.5.31

猜你喜欢

转载自blog.csdn.net/xiaowude_boke/article/details/130959793