We are often asked in interviews about the difference between a watch and computed, so today we are going to talk about what it does and what the difference is

What does computed do

computed:{
    Name:function(){
        return this.firstname+this.lastname; }}Copy the code

Computed attributes automatically listen for changes in dependency values to dynamically return content. A listener is a procedure that triggers a callback when the value of the listener changes and does something like this: When firstName and lastName change, the value of Name is triggered. Okay

What does a watch do

watch:{
	num:function(val,oldval){
	    console.log(val,oldval); }}Copy the code

When the value of the defined variable changes, the corresponding method will be called as shown in the above code. When the value of num changes, the method of NUM will be called. The parameters in the method correspond to the new and old values of num

The difference between the two

  1. Difference in usage: Calculated properties: when only dynamic values are needed; Watch listens: You need to know the business logic to execute after the value changes
  2. The difference between declarations is that calculating the value of an attribute is itself a declaration. The value that watch listens to needs to be declared in data