Vue uses Compition API to generate computed properties computed

overview

As programmers, we all know that writing code not only needs to efficiently complete the requirements, but also make our code elegant and more maintainable. And maintainability refers to the readability of the code, because the code we write is the property of the company. When it needs to be maintained by others, the more readable code will make the person who maintains your code get started faster. The computed properties mentioned in this article are for this purpose. Computed properties can make our code look less bloated, more readable and maintainable, so before introducing the use of Compition Api to generate calculated properties, we need to first Introduce what is a computed property.

1. Computed properties

1.1 Introduction and use of computed properties

Vue’s expressions are very powerful and convenient, but it’s okay to write simple operations. Although there is no big problem with complex operations, it will make the code bloated, resulting in poor readability and difficult to maintain. Refer to the examples on the official website to understand computed properties.

.........省略开头代码.......
  data() {
    
    
    return {
    
    
      author: {
    
    
        name: 'John Doe',
        books: [
          'Vue 2 - Advanced Guide',
          'Vue 3 - Basic Guide',
          'Vue 4 - The Mystery'
        ]
      }
    }
  }
 .........

Suppose you want to display different information according to whether the author has some books, if you use the expression as follows:

<p>是否有已经发布的书籍:</p>
<span>{
    
    {
    
     author.books.length > 0 ? 'Yes' : 'No' }}</span>

The above code looks a bit complicated. If we need to write this 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 small partners will say to use the method to extract, and I will introduce why not use the method later.
After using computed properties, the above requirements can be achieved in the following way. We can use the computed keyword provided by Vue to define computed properties:

.............省略开头代码.....
  data() {
    
    
    return {
    
    
      author: {
    
    
        name: 'John Doe',
        books: [
          'Vue 2 - Advanced Guide',
          'Vue 3 - Basic Guide',
          'Vue 4 - The Mystery'
        ]
      }
    }
  },
  computed: {
    
    
    // 一个计算属性的 getter
    publishedBooksMessage() {
    
    
      // `this` 指向当前组件实例
      return this.author.books.length > 0 ? 'Yes' : 'No'
    }
  }
  ..........

In the code above, 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 the publishedBooksMessage will also change accordingly. Computed properties are used in templates in the same way as regular properties. Vue will detect that this.publishedBooksMessage depends on this.author.books, so when this.author.books changes, any bindings that depend on this.publishedBooksMessage will update at the same time.
(Quoted from the Vue official website computed properties chapter)

1.2 The difference between computed properties and methods

Now let's explain why Vue provides a computed property instead of a method? Let's continue to look at the example to explain. Still using the above example, we can also use methods to complete the requirements

// 定义一个方法来判断是否有新发布的作品
methods: {
    
    
  calculateBooksMessage() {
    
    
    return this.author.books.length > 0 ? 'Yes' : 'No'
  }
}

// 调用方法
<p>{
    
    {
    
     calculateBooksMessage() }}</p>

As shown in the above code, when we use methods to achieve the above requirements, the execution results are exactly the same. The difference is that the computed attribute will be a cache, as long as the variables involved in the calculation in the computed attribute 计算属性值会基于其响应式依赖被缓存。一个计算属性仅会在其响应式依赖更新时才重新计算。这意味着只要 author.books 不改变,无论多少次访问 ,publishedBooksMessage 都会立即返回先前的计算结果,而不用重复执行 getter 函数correspond to If the dependency is not updated, the computed property will return the cached value, and will be recalculated if there is an update. For example, in this example books, as long as we don’t books中add new books, the calculated property publishedBooksMessagewill always return the previously calculated value and will not trigger recalculation. However, if we use the method, the method will be executed every time, regardless of whether a new book is added or not. . This will waste CPU resources. Although it is not much, it can be saved if it can be saved.

Another advantage of using computed properties is that it is fast. Imagine that you have a large list that you want to render. If you use the method, whether you update the list or not, you need to perform a traversal operation to get the length. However, using computed properties, calculated After one time, as long as there is no update later, the cache can be used, which can improve the response speed of the page.

1.2 Writable Computed Properties

Computed properties are read-only by default. When you try to modify a computed property, you will receive a runtime warning. Because computed properties are mainly cached, random writing will destroy the previously cached value, resulting in an unexpected value when the cached value is retrieved next time. Usually we only need to use "writable" properties in some special scenarios. Writable computed properties can be created by providing getters and setters at the same time. The code is as follows:

  data() {
    
    
    return {
    
    
      firstName: 'John',
      lastName: 'Doe'
    }
  },
  computed: {
    
    
    fullName: {
    
    
      // getter
      get() {
    
    
        return this.firstName + ' ' + this.lastName
      },
      // setter
      set(newValue) {
    
    
        // 注意:我们这里使用的是解构赋值语法
        [this.firstName, this.lastName] = newValue.split(' ')
      }
    }
  }

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

Generating computed properties using the Compition API

Generating computed properties in the Compition API is actually writing the computed properties 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>computed的使用</title>
    <script src="https://unpkg.com/vue@next"></script>
</head>
<body>
    <div id="root"></div>
</body>
<script>
const app = Vue.createApp({
    
    
    setup(){
    
    
        const{
    
    ref, computed} = Vue;
        const count = ref(0);
        const handleClick = ()=>{
    
    
            count.value += 1;
        }
        // 操作基本类型的值
        // const countAddFive = computed(()=>{
    
    
        //     return count.value + 5;

        // });
        let countAddFive = computed({
    
    
            get:() =>{
    
    
                return count.value + 5;
            },
            set:(param)=>{
    
    
                count.value = param  - 5;
            } 
        }) 
        setTimeout(()=>{
    
    
            countAddFive.value = 100;
        },3000)

        return {
    
    count,handleClick,countAddFive}
        },
   template:
         `
        <div>
            <span @click="handleClick">{
     
     {count}}--------{
     
     {countAddFive}}</span>
        </div>
         `
 });
        
 const vm = app.mount('#root');
</script>

In the above code, when we use the calculated property in the setup, we need to introduce it in advance const{ref, computed} = Vue;and then use it in the 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 and countAddFive. When clicking
, the value of count will be increased by one, and the value of countAddFive will be increased by 5. After 3 seconds, change the value of countAddFive to 100, and then count becomes 95 because

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

When the value of conutAddFive is set, the value of count will be reduced by 5.

Summarize

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

Guess you like

Origin blog.csdn.net/zxj2589/article/details/130777948