computed和watch都可以用来在某个数据发生改变时,在程序做出相应的响应。可以根据具体的使用情况进行选择。例如:
computed: {
fullName: function() {
return this.firstName + ' ' + this.lastName;
}
},
watch: {
firstName: function(newValue) {
this.fullName = newValue + ' ' + this.lastName;
},
lastName: function(newValue){
this.fullName = this.firstName + ' ' + newValue;
}
}
- 当多个变量中任意的变量发生改变都会引起调用时,使用computed
- 当组件未对变量做声明,不过还想根据实际情况做出响应时,使用computed
- 当这个响应发生后,需要调用异步方法时,使用watch
- computed 默认是读取。如果想要改变返回值需要使用set方法
- watch即可以读取,也可以重新赋值。