1. Computed, Methods and Watch
| – computed (calculate attribute)
| - based on their response type rely on caching | - monitor their own define variables, this variable is defined inside the computed directly, not the data definition. | - for more than one variable or object returns a result value after processing. Multiple affects one. | - dependent data only, when dependent data change, will recount. So for any complex logic, you should use computed properties.Copy the code
| – watch (the listener)
| - when the need to change the data to perform asynchronous or overhead operation, this method is the most useful, such as: allowed to execute asynchronous operations (access an API), limits to perform the operation frequency, before get the final result, set up an intermediate state. Computing properties cannot do this. | - is mainly used in monitoring changes of the vue instance, monitoring of variables must be declared in the data. You can monitor a single variable or an entire object. A affect multiple. | - often used to monitor routing, and other special processing input input box. There is no cacheCopy the code
| – the methods (event handling)
Define functions that need to be triggered by active calls. Each call is recalculated. There is no cacheCopy the code
The difference between:
| - on the mechanism of action: | - computed and watch is based on dependent on tracking mechanism, such as: when a based on data change, all depend on the data of "relevant" change "automatic", a popular speak be automatically call related function to realize the data changes, | - the Methods similar tofunction, need to manually to call, not like a computed, watch "automatically" predefined function | - nature: | - is Computed to calculate attribute, fact and data in a data object properties in use is the same class, a data influenced by multiple data | - it's function, the Methods to define clearly need like "func ()" generally to call, does not handle the data logical relationship, Provide only callable function | - Watch: similar to the surveillance mechanism + event mechanism, a data affect multiple dataCopy the code
Practical examples:
1. Add up the bill:
Using computed attributes:
Calculate the amount variable and return the result. If you define the variable twice, an error will appear as shown in the following figureCopy the code
Results:
The above amount is transferred to methods and amount attribute variable function, and the results are consistentCopy the code
Watch demonstrations:
When you change the team name, the corresponding member’s team name also changes
The results of
Refer to the reproduced record:
Full analysis of vUE’s computed and Watch details
【Vue】 Talk about Vue dependency tracking system — Understand the difference and connection between Methods watch and compute
Little White note ~~~~