1、区别
watch中的函数是不需要调用的
computed内部的函数调用的时候不需要加(),因为内部不是函数,而是属性对象只有get方法时的简写。
watch 属性监听 监听属性的变化
computed:计算属性通过属性计算而得来的属性
watch需要在数据变化时执行异步或开销较大的操作时使用
对于任何复杂逻辑或一个数据属性在它所依赖的属性发生变化时,也要发生变化,这种情况下,我们最好使用计算属性computed。
默认是getter方法,在页面中直接使用{{reversedMessage}}。
computed 属性的结果会被缓存,除非依赖的响应式属性变化才会重新计算。主要当作属性来使用;
computed中的函数必须用return返回最终的结果
computed: {
// 计算属性的getter
reversedMessage: function () {
console.log('调用了');
return this.message.split('').reverse().join('');
}
},
Computed还有一个setter方法:
fullName: {
// getter
get: function () {
console.log('get');
return this.firstName + ' ' +this.lastName;
},
// setter
set: function (newValue) {
this.firstName = '120';
this.lastName = '021';
console.log('set');
}
}
当computed中的函数所依赖的属性如果没有发生改变的时候,那么调用当前函数的时候结果会从缓存中读取
watch 一个对象,键是需要观察的表达式,值是对应回调函数。主要用来监听某些特定数据的变化,从而进行某些具体的业务逻辑操作;
watch: {
firstName: function (val) {
this.fullName = val + ' ' +this.lastName
},
lastName: function (val) {
this.fullName = this.firstName + '' + val
}
}
2、使用场景
computed
当一个属性受多个属性影响的时候就需要用到computed
最典型的例子: 购物车商品结算的时候
watch
当一条数据影响多条数据的时候就需要用watch
搜索数据