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

How to get the width and height of the image in WeChat applet

origin Recently, I am working on requirement A, i...

Vue implements fuzzy query-Mysql database data

Table of contents 1. Demand 2. Implementation 3. ...

Introduction to Apache deployment of https in cryptography

Table of contents Purpose Experimental environmen...

Vue+echarts realizes stacked bar chart

This article shares the specific code of Vue+echa...

How to reset MySQL root password

Table of contents 1. Forgot the root password and...

How to change apt-get source in Ubuntu 18.04

When using apt-get to install, it will be very sl...

Tips and precautions for using MySQL index

1. The role of index In general application syste...

Introduction to using Unicode characters in web pages (&#,\u, etc.)

The earliest computers could only use ASCII chara...

Making a simple game engine with React Native

Table of contents Introduction Get started A brie...

Steps for importing tens of millions of data into MySQL using .Net Core

Table of contents Preliminary preparation Impleme...

A method of making carousel images with CSS3

Slideshows are often seen on web pages. They have...

How to set up vscode remote connection to server docker container

Table of contents Pull the image Run the image (g...