Detailed explanation of computed properties in Vue

Detailed explanation of computed properties in Vue

Today, let's talk about the computed property in Vue. In order to better understand the benefits of computed properties, let's first slowly understand the computed properties through a case. There is the following case: define two input boxes and a span tag. The content in the span tag is the value of the two input boxes. The content in the span tag changes with the content in the input box.

Interpolation Expressions

We first use the interpolation expression method to achieve this effect

 <body>
    <div id="app">
        Last Name: <input type="text" v-model=firstName> </br>
        </br>
        Name: <input type="text" v-model=lastName></br>
        </br>
        Name: <span>{{firstName}}{{lastName}}</span>
​
    </div>
</body>
<script type="text/javascript">
    new Vue({
        el: "#app",
        data: {
            firstName: '张',
            lastName: '三'
        },
        methods: {
        }
    })
​
</script> 

We can find that we can easily achieve the effect we need, but if I want to add another requirement now, when I enter English, the first letter should be capitalized. At this time, we can only use the following method

 <body>
    <div id="app">
        firstName: <input type="text" v-model=firstName> </br>
        </br>
        lastName: <input type="text" v-model=lastName></br>
        </br>
        fullName: <span>{{firstName.replace(firstName[0],firstName[0].toUpperCase())}} {{lastName.replace(lastName[0],lastName[0].toUpperCase())}}</span>
​
    </div>
</body>
<script type="text/javascript">
    var str = ''
​
    new Vue({
        el: "#app",
        data: {
            firstName: 'joe',
            lastName: 'lili'
        },
        methods: {
        }
    })
</script> 

From the interpolation expression, it can be seen that although the desired effect can be achieved, the code is very lengthy and not easy to read. At this time, it is thought that a method can be added to methods to achieve this effect.

methods

Add the fullName method to methods

 <body>
    <div id="app">
        firstName: <input type="text" v-model=firstName> </br>
        </br>
        lastName: <input type="text" v-model=lastName></br>
        </br>
        fullName: <span>{{fullName()}}</span>
​
    </div>
</body>
<script type="text/javascript">
    var str = ''
​
    new Vue({
        el: "#app",
        data: {
            firstName: 'joe',
            lastName: 'lili'
        },
        methods: {
            fullName() {
                let a = '';
                let b = '';
                if (this.firstName.length != 0)
                    a = this.firstName.replace(this.firstName[0], this.firstName[0].toUpperCase())
                if (this.lastName.length != 0)
                    b = this.lastName.replace(this.lastName[0], this.lastName[0].toUpperCase())
                return a + ' ' + b
            }
        }
    })
​
</script>

We can see that the problem of too long code can be solved well through methods. But we are faced with another problem. When we study the data attribute in vue, we know that as long as the data in data changes, the places where data is used in the page will be updated. Therefore, when the data firstName and lastName change, the method fullName will be called again, which will lead to low code efficiency under certain circumstances. In addition, the methods in methods will be run as many times as they are used in the interpolation expression. Based on the drawbacks of the above two methods, another method has emerged, which is to use computed properties.

computed

Some properties can be defined in computed: calculated properties. The essence of a calculated attribute is actually a method, but it can be used directly as an attribute when in use. The specific features are as follows

  • When using calculated properties, you don't need to add () and just write the name.
  • If the calculated property uses the data in data, when the data changes, the value of the calculated property will be recalculated immediately
  • The result of the calculated property is cached when it is first used, and the result of the calculated property is not re-evaluated until the data that the property depends on changes.
 <body>
    <div id="app">
        firstName: <input type="text" v-model=firstName> </br>
        </br>
        lastName: <input type="text" v-model=lastName></br>
        </br>
        fullName: <span>{{fullName}}</span></br>
        </br>
        fullName: <span>{{fullName}}</span></br>
        </br>
        fullName: <span>{{fullName}}</span>
​
    </div>
</body>
<script type="text/javascript">
    var str = ''
​
    new Vue({
        el: "#app",
        data: {
            firstName: 'joe',
            lastName: 'lili'
        },
        computed: {
            //What is the function of get? When fullName is read, get is called, and the return value is the value of fullName. //When is get called? 1. When fullName is read for the first time. 2. When the dependent data changes fullName: {
                get() {
                    console.log('hi, I called computed')
                  let a = '';
                let b = '';
                if (this.firstName.length != 0)
                    a = this.firstName.replace(this.firstName[0], this.firstName[0].toUpperCase())
                if (this.lastName.length != 0)
                    b = this.lastName.replace(this.lastName[0], this.lastName[0].toUpperCase())
                return a + ' ' + b
                }
            }
        }
    })
</script>
</html> 

We have said before that if a method in methods is used n times in a page, it will be called n times, but this will not happen with properties in computed. In the above code, we used the same calculated property three times in the page but only output the result once. Similarly, we used the full method in methods but output the result three times, which means that the method was called three times. Why did this happen? This is because there is a caching mechanism in computed but not in methods. When the code parses the first fullName, the result of fullName will be cached. When the second and third fullName are parsed, it will be found that the result is already in the cache, so it will not be called.

Now that we have a general understanding of the use of computed, let's supplement it.

In computed, we can achieve the assignment effect by adding a set method to the calculated property

 <body>
    <div id="app">
        firstName: <input type="text" v-model=firstName> </br>
        </br>
        lastName: <input type="text" v-model=lastName></br>
        </br>
        fullName: <span>{{fullName}}</span></br>
        </br>
    </div>
</body>
<script type="text/javascript">
    var str = ''
​
    var app = new Vue({
        el: "#app",
        data: {
            firstName: 'joe',
            lastName: 'lili'
        },
        computed: {
            //What is the function of get? When fullName is read, get is called, and the return value is the value of fullName. //When is get called? 1. When fullName is read for the first time. 2. When the dependent data changes fullName: {
                get() {
                    console.log(this)
                    return this.firstName + this.lastName
                },
                set(val) {
                    this.firstName = val[0]
                    this.lastName = val[1]
                }
            }
        }
    })
​
</script>

We can see that when assigning a value to fullName in the console, both firstName and lastName will change.

If there is only get and no set in the calculated property, you can write it directly like the following code

 computed: {
            fullName(){
                console.log(this)
                return this.firstName + this.lastName
                }
            }

Summarize

This article ends here. I hope it can be helpful to you. I also hope you can pay more attention to more content on 123WORDPRESS.COM!

You may also be interested in:
  • Usage and demonstration of ref in Vue
  • Vue computed properties
  • setup+ref+reactive implements vue3 responsiveness
  • How to understand the difference between ref toRef and toRefs in Vue3
  • Do you know ref, computed, reactive and toRefs of Vue3?

<<:  10 Website Usability Tips Everyone Should Know

>>:  Complete steps to enable gzip compression in nginx

Recommend

JavaScript function syntax explained

Table of contents 1. Ordinary functions 2. Arrow ...

A brief introduction to the usage of decimal type in MySQL

The floating-point types supported in MySQL are F...

The implementation of Youda's new petite-vue

Table of contents Preface Introduction Live Easy ...

What do CN2, GIA, CIA, BGP and IPLC mean?

What is CN2 line? CN2 stands for China Telecom Ne...

Detailed explanation of nginx reverse proxy webSocket configuration

Recently, I used the webSocket protocol when work...

JavaScript implements AI tic-tac-toe game through the maximum and minimum algorithm

Without further ado, let’s run the screenshot dir...

MySQL series tutorials for beginners

Table of contents 1. Basic concepts and basic com...

How to run the react project on WeChat official account

Table of contents 1. Use the a tag to preview or ...

MySQL query specifies that the field is not a number and comma sql

Core SQL statements MySQL query statement that do...

How to configure two-way certificate verification on nginx proxy server

Generate a certificate chain Use the script to ge...

What is Nginx load balancing and how to configure it

What is Load Balancing Load balancing is mainly a...

Vue implements a movable floating button

This article example shares the specific code of ...