A brief discussion on computed properties (computed) in Vue

The concept of computed properties:

A computed property in Vue.js is a property used to derive data. Computed properties rely on existing reactive data and automatically update when the data changes. Computed properties are different from ordinary data properties in that they return calculated results by defining a function instead of directly storing a value. A computed property is recalculated every time the data it depends on changes.

Let’s learn more about computed through two examples!

Example 1

Here is an example that demonstrates how to use calculated properties to calculate the total price of items in a shopping cart:

<template>
  <div>
    <ul>
      <li v-for="product in products" :key="product.id">
        {
    
    {
    
     product.name }} - {
    
    {
    
     product.price }}
      </li>
    </ul>
    <p>商品总价:{
    
    {
    
     totalPrice }}</p>
  </div>
</template>

<script>
export default {
    
    
  data() {
    
    
    return {
    
    
      products: [
        {
    
     id: 1, name: '商品1', price: 100 },
        {
    
     id: 2, name: '商品2', price: 200 },
        {
    
     id: 3, name: '商品3', price: 300 },
      ],
    };
  },
  computed: {
    
    
    totalPrice() {
    
    
      return this.products.reduce((total, product) => total + product.price, 0);
    },
  },
};
</script>

In the above code, we create an array products containing multiple products. Each product object contains id, name and price attributes. By calculating the attribute totalPrice, we use the reduce() function to accumulate the product array and calculate the total price of the product.
In the template, we display the value of the calculated property on the page through the interpolation syntax { { totalPrice }}. When the products array changes, the calculated property totalPrice is automatically recalculated and the displayed total price is updated.
By using computed properties, we can easily derive the required data without having to manually manage and update them.

Example 2

new Vue({
    
      
  el: '#app',  
  data: {
    
      
    firstName: 'John',  
    lastName: 'Doe'  
  },  
  computed: {
    
      
    fullName: {
    
      
      // 属性获取函数 
      get: function () {
    
      
        return this.firstName + ' ' + this.lastName;  
      },  
      // 属性设置函数  
      set: function (newValue) {
    
      
        var names = newValue.split(' ');  
        this.firstName = names[0];  
        this.lastName = names[1];  
      }  
    }  
  }  
})

In this example, fullName is a computed property calculated from firstName and lastName. In the get function, we access the data of the Vue instance through this.firstName and this.lastName. In the set function, we split the string into two parts according to spaces and update the values ​​of firstName and lastName.
In addition to using the data and methods of the Vue instance in computed properties, we can also define our own variables or data and use them in computed properties. These properties can be local variables or externally defined variables, depending on how the computed property is implemented.

Advantages and Disadvantages of Computed Properties:

advantage:

1. Responsive : Calculated properties will automatically respond to data changes. When the data they depend on changes, the calculated properties will be recalculated and related components will be updated. This allows developers to easily create responsive interfaces.

2. Caching mechanism : Computed attributes have a caching mechanism and will only be recalculated when the data it depends on changes. If multiple components depend on the same computed property, and its dependent data has not changed, the value of the computed property will be cached, improving computing performance.

3. Maintainability : Through calculated properties, we can encapsulate complex logic in a function, making the code clearer and more readable. They provide a way to organize and manage derived data, making code more maintainable.

shortcoming:

1. Computational overhead : Calculated attributes are calculated based on existing data, and some complex calculation logic may occupy more computing resources. When the amount of dependent data is large or the calculation logic is complex, the performance of calculated attributes may be affected.

2. Immutability : Computed properties are read-only, they cannot directly modify the original data. Computed properties rely on other data for their calculations, but cannot directly modify this data. If you need to modify the data, you need to use other methods, such as methods or listeners.

To sum up, Vue.js computed properties are very useful when developing responsive interfaces and can provide convenient derived data and caching mechanisms. But when encountering complex computing logic or large amounts of data, you need to pay attention to computing overhead and performance issues.

Scenarios for using computed:

Used to handle complex logical operations;
one data is affected by one or more data;
used to handle situations that watch and methods cannot handle, or are inconvenient to handle.
Process complex expressions in templates, the changing relationship between the number of items in the shopping cart and the total amount, etc.

There are several points to note when using computed:

1. Called when initializing the display or when related data, props and other attribute data change;
2. The calculated attribute is not in data. It is a new value obtained by calculation based on the data in data or props. This new value is based on the known Changes when the value changes;
3. Define the method of calculating the attribute in the computed attribute object, which is the same as getting the data attribute in the data object, and calls it in the form of attribute access; 4.
If the computed attribute value is a function, then get will be used by default The method must have a return value, and the return value of the function is the attribute value of the attribute;
5. The computed attribute value will cache the calculation result by default. In repeated calls, as long as the dependent data remains unchanged, the calculation result in the cache will be taken directly. Only when the dependent data changes, computed will be recalculated;
6. In computed, the attributes have a get and a set method. When the data changes, the set method is called.

Caching was mentioned above, so how does computed implement caching?

In Vue.js, the caching of computed properties is implemented through internal dependency tracking and caching mechanisms. When a computed property is accessed, Vue.js
marks it as a reactive dependency and caches its return value. Computed properties are recalculated and cached values ​​are updated only when the reactive data on which the computed property depends changes.

Specifically, the cache implementation process of computed attributes is as follows:

  1. When a computed property is called in data binding in a template or in a component method, Vue.js creates a dependency that associates the computed property with the reactive data it depends on.
  2. In the computed property's getter function, Vue.js checks whether the computed property already has a cached value. If there is, the cached value is returned directly without recalculation.
  3. If the calculated property does not have a cached value, the computed property's getter function is executed and the calculated result is cached.
  4. During the execution of the computed property getter function, when other reactive data is accessed, Vue.js adds this data to the dependencies and establishes the reactive dependency chain.
  5. When the reactive data it depends on changes, Vue.js will notify the dependency of the calculated property and mark the calculated property as "dirty". This means that the value of the computed property needs to be recalculated.
  6. When the calculated property is accessed again, if the calculated property is marked as "dirty", Vue.js will re-execute the getter function of the calculated property and cache the calculated result.

Through this dependency tracking and caching mechanism, Vue.js can intelligently update and calculate the value of calculated properties when data changes, avoiding unnecessary repeated calculations and improving performance.

new Vue({
    
      
  el: '#app',  
  data: {
    
      
    count: 0,  
    message: 'Hello'  
  },  
  computed: {
    
      
    doubleCount: {
    
      
      get: function () {
    
      
        console.log('get called');  
        return this.count * 2;  
      },  
      set: function (newValue) {
    
      
        console.log('set called');  
        this.count = newValue / 2;  
      }  
    }  
  }  
})

In this example, doubleCount is a computed property that depends on the count data property. In the get function, we print "get called" and then return twice the count. In the set function, we print "set called" and then set the value of count to half the value passed in. When we get the doubleCount property for the first time, since the count has not changed, the calculated property will use the property value in the cache and the get function will not be called, so "get called" will not be printed. If we change the value of count, the computed property will recalculate doubleCount and call the set function, printing "set called". If we get the doubleCount property again, the calculated property will use the property value in the cache and the get function will not be called again, so "get called" will not be printed again.
This example demonstrates the caching mechanism for computed properties. Computed properties are recalculated only when the dependent data property changes, otherwise the property value in the cache is used.

Note: The cache of computed properties is only for the computed properties themselves. If the reactive data that a computed property relies on changes, but the logic of the computed property does not use that data for calculations, the value of the computed property will not be updated. In this case, you can use watch to monitor data changes and perform corresponding operations.

If you have anything to add, please leave a message in the comment area!

Guess you like

Origin blog.csdn.net/He_9a9/article/details/132708211