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

Detailed explanation of JavaScript upload file limit parameter case

Project scenario: 1. Upload file restrictions Fun...

Example of automatic stop effect after text scrolling

The effect is very simple, just copy the following...

CSS Skills Collection - Classics among Classics

Remove the dotted box on the link Copy code The co...

Implementation of adding remark information to mysql

Preface Some people have asked me some MySQL note...

MySQL 5.7.17 installation graphic tutorial (windows)

I recently started learning database, and I feel ...

Implementation steps for docker deployment of springboot and vue projects

Table of contents A. Docker deployment of springb...

Docker deploys Mysql, .Net6, Sqlserver and other containers

Table of contents Install Docker on CentOS 8 1. U...

A brief discussion on the binary family of JS

Table of contents Overview Blob Blob in Action Bl...

Native js to realize bouncing ball

On a whim, I wrote a case study of a small ball b...

【HTML element】Detailed explanation of tag text

1. Use basic text elements to mark up content Fir...

6 solutions for network failure in Docker container

6 solutions for network failure in Docker contain...