1. Realize that vUE is computed

1. Why is computed

For complex logic, writing it directly in the template would make the template too heavy and difficult to maintain,

Here is a simple example where the template is rendered based on data A and B

Before button click:

Contrast clicking the button with a = 0 does not display the div

We can see that the results computed using the computed attribute are the same as those computed directly in the template, but the results will not change if computed directly during initialization, indicating that the computed attribute will track the changes in the dependent data and thus recalculate.

In which lifecycle was 2.computed created

Computed initialization occurs between the beforeCreated and created life cycles

3. The computed attributes are cached based on the responsive dependencies and are recalculated only when the dependent attributes change

Some people think that using methods is the same as using computed, and we can use methods to achieve the same results, so why use computed attributes? Let’s take a look at the following example

The result of triggering the method: we can see that the method is recalculated each time it is executed (this is not a very good example, we can consider or assume that the self-addition is a complex algorithm).

The result of computed properties: the return is constant each time, indicating that computed has computational properties, which can also be viewed as a memory function

4.computed The system does not support asynchrony. Data changes cannot be monitored for asynchronous operations on the computed system

We can see that no result is returned even after 3 seconds

5.computed property has get and set methods. If the value of the property is a function, the default method is get. If data changes, the set method is used to define computed

This section describes the application scenarios of 3.computed

1. When multiple values need to be recalculated to generate a new value, use the computed attribute, many-to-one relationship

2. When you need to perform complex operations and want to reduce the number of operations through caching to improve performance, you can use the calculation attribute

4. Vue3 allows you to listen to an array without changing its length, without using $set