SoFunction
Updated on 2025-04-04

Vue uses Composition API to generate computed compute properties

Overview

As programmers, we all know that writing code not only requires efficient completion of requirements, but also requires making our code elegant and maintainable. Maintainability is the readability of the code, because the code we write is the company's property. When others need to maintain it, higher readability code will make the person who maintains your code faster. The computed computed attributes mentioned in this article are for this purpose. Computed attributes can make our code look less bloated, readable and maintainable. Therefore, before introducing the use of Compition Api to generate computed attributes, we need to introduce what computed attributes are.

1. Calculate properties

1.1 Introduction and use of computed attributes

Vue's expressions are very powerful and convenient, but writing simple operations is OK. Although complex operations are not a big problem, they will make the code very bloated, resulting in poor readability and difficult to maintain. Quote the examples from the official website to understand the computational properties.

//......Omit the beginning code......  data() {
    return {
      author: {
        name: 'John Doe',
        books: [
          'Vue 2 - Advanced Guide',
          'Vue 3 - Basic Guide',
          'Vue 4 - The Mystery'
        ]
      }
    }
  }

Suppose that there are some books to display different information based on whether author already has them, if expressions are used, the following way is:

<p>Are there any books that have been published:</p>
<span>{{  > 0 ? 'Yes' : 'No' }}</span>

The above code seems to be a bit complicated. If we need to write this way in many places in the interface, it will be too bloated, and the same code is written everywhere. So computed properties are introduced to optimize this problem. Maybe many friends will say that they use methods to extract, and they will introduce why they don’t use methods later. After using the computed attributes, the above requirements can be implemented in the following way. We can use the computed keywords provided by Vue to define computed attributes:

//.........Omit the beginning code...  data() {
    return {
      author: {
        name: 'John Doe',
        books: [
          'Vue 2 - Advanced Guide',
          'Vue 3 - Basic Guide',
          'Vue 4 - The Mystery'
        ]
      }
    }
  },
  computed: {
    // A getter that calculates properties    publishedBooksMessage() {
      // `this` points to the current component instance      return  > 0 ? 'Yes' : 'No'
    }
  }
//  ..........

In the above code, we define a computed property publishedBooksMessage here. When we change the value of the books array in the data of this application, we can see that publishedBooksMessage will also change. The way to use computed properties in a template is no different from the general properties. Vue will detect dependencies, so when changes, any dependent bindings will be updated at the same time.(Quote from the Computing Attributes Chapter of Vue Official Website)

1.2 Differences between calculation properties and methods

Now let’s explain why Vue does not use methods, but instead provides a computed attribute? Let's continue to look at examples to explain. Or use the above example, we can also use methods to complete the requirements.

// Define a method to determine whether there are new works publishedmethods: {
  calculateBooksMessage() {
    return  > 0 ? 'Yes' : 'No'
  }
}
// Call method<p>{{ calculateBooksMessage() }}</p>

As shown in the above code, when we use methods to implement the above requirements, the execution results are indeed completely consistent, the difference is that the calculated attribute value is cached based on its responsive dependencies. A computed property is recalculated only when its responsive dependencies are updated. This means that as long as it does not change, no matter how many times it is accessed, publishedBooksMessage will immediately return the previous calculation result without repeatedly executing the getter function. That is to say, the calculated attribute will be cached. As long as the corresponding dependencies of the variables participating in the calculation in the calculation attribute are not updated, the calculated attribute will return the cached value, and the calculation will be recalculated only if there is an update. For example, in this examplebooksAs long as we don't goIn booksAdd a new book, then calculate the propertiespublishedBooksMessageThe previously calculated value will be returned and the recalculation will not be triggered. If you use the method, the method will be executed every time, regardless of whether a new book is added. This will waste CPU resources. Although it is not much, it can save as much as possible.

Another advantage of using computed attributes is that they are fast. Imagine that you have a large list that you want to render. If you use it, you need to go through the length operation whether you update the list or not. However, if you use computed attributes, you can use cache as long as there is no update later, so that the page response speed can be improved.

1.3 Writable Computational Properties

Computed properties are read-only by default. When you try to modify a computed property, you will receive a runtime warning. Because the computed attributes are mainly cached, if you write them at will, it will destroy the previously cached value, resulting in the value not expected the next time you fetch the cached value. Generally, we only need to use "writable" attributes in certain special scenarios. Writable computed attributes can be created by providing both getters and setters. The code is as follows:

  data() {
    return {
      firstName: 'John',
      lastName: 'Doe'
    }
  },
  computed: {
    fullName: {
      // getter
      get() {
        return  + ' ' + 
      },
      // setter
      set(newValue) {
        // Note: We are using deconstructed assignment syntax here        [, ] = (' ')
      }
    }
  }

In the above code, when = 'John Doe' is called, the setter will be called and and will be updated accordingly. The get() method is called every time you get a value, and the set method is called every time you get a value.

2. Use the Compition API to generate computed properties

Generating computed attributes in the Compition API is actually writing the computed attributes used in traditional Vue into the setup function. The code is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>computedUse</title>
    <script src="/vue@next"></script>
</head>
<body>
    <div ></div>
</body>
<script>
const app = ({
    setup(){
        const{ref, computed} = Vue;
        const count = ref(0);
        const handleClick = ()=>{
             += 1;
        }
        // Operate the value of the basic type        // const countAddFive = computed(()=>{
        //     return  + 5;
        // });
        let countAddFive = computed({
            get:() =>{
                return  + 5;
            },
            set:(param)=>{
                 = param  - 5;
            } 
        }) 
        setTimeout(()=>{
             = 100;
        },3000)
        return {count,handleClick,countAddFive}
        },
   template:
         `
        <div>
            <span @click="handleClick">{{count}}--------{{countAddFive}}</span>
        </div>
         `
 });
 const vm = ('#root');
</script>

In the above code, we need to introduce it in advance when using computed properties in setup. const{ref, computed} = Vue;Then it is used in setup(). The usage is very simple and it is already very clear in the code. The meaning of the code demo is also very simple, which is to display two values ​​count, countAddFive. When clicking, add one to countAddFive, add 5 to countAddFive. After 3 seconds, change the value of countAddFive to 100, and then the value of count will become 95, because

 set:(param)=>{
                 = param  - 5;
            } 

Setting the value of conutAddFive will decrement the value of count by 5.

Summarize

This article mainly introduces computed attributes and the use of computed attributes in the Compition API. After learning this article, we need to understand under what circumstances we need to use computed attributes, the difference between computed attributes and methods. And to understand how writable computed properties are used. The use of computed attributes can greatly speed up the response speed of our interface. It is recommended that readers master the use of computed attributes, and then apply computed attributes to the corresponding places in the project according to the scene.

The above is the detailed content of Vue using the Composition API to generate computed computing attributes. For more information about computed Vue computed computing attributes, please follow my other related articles!