vue calculated attribute

vue calculated attribute

(1) Basic example

Sometimes we need to use the data a in the template. At this time, we need to use the expression, but in some places, we need to do some simple processing on the data a before we can use it. Then we will write some js logical operations in the expression. For example, now we need to realize the calculation of twice the value of num,

<div id="app">
        <p><button @click="num++">click</button></p>
        <p>num: {{num}}</p>
        <p>num*2: {{num*2}}</p>
        <p><input type="text" v-model='msg'></p>
    </div>

Disadvantages: if this calculation is used in many places, it will be troublesome to modify later

(2) Method of encapsulating function

We can encapsulate the contents of multiple operations into a function to call

   <p>method:{{doubleNum()}}</p>
var vm = new Vue({
            el:"#app",
            data:{
                num:1,
            },
		methods:{
                doubleNum(){
                    return this.num*2 
                }
      	 }
      	 })

However, at this time, as long as there are data changes in the vm, the changed data may have nothing to do with the data we pay attention to, but the vm will re render the template. At this time, the methods in the expression will be re executed, which will greatly affect the performance

(3) This function is realized through the watch listener

watch can monitor the changes of existing data, and then when the existing data changes, some business logic will be implemented internally

<div id="app">
        <p><button @click="num++">click</button></p>
        <p>watchNum: {{watchNum}}</p>
    </div>
<script>
  var vm = new Vue({
            el:"#app",
            data:{
                num:1,
                watchNum:''
            },
            watch:{
                //Monitor the change of num value. Once num changes, make watchNum twice the new value after change
                //Set the watch attribute in the vm instance, and set some monitoring through key value pairs. The key name is the data name, and the value can be a function 				   This function will not be executed until the data is changed. The two parameters are the value before and after the change
                 // num:function(newValue,oldValue){
                 // this.watchNum = newValue*2
                 // }
                num:{
                   // The value can also be a method name, which will be executed when the data changes
					//When the data is object, the change of the key value pair of the object will not be monitored (the push and other methods of the array can). At this time, it is necessary to set deep monitoring:
                    immediate:true, //The delegate is also allowed to execute once during initialization
                    handler:function(newValue){
                        this.watchNum = newValue*2
                    }
                }  
            }
        })
</script>
(4)computed property

‚Äč The writing method of calculating attributes is a function, but it must not be called with parentheses when calling above.

A new data will be generated based on the existing data, and the two will be associated to establish a permanent cache.

In addition, when the irrelevant data is changed, the internal calculation of the calculation attribute will not be recalculated, but the data can be directly fetched from the cache

<div id="app">
        <p><button @click="num++">click</button></p>
        <p>computedNum: {{computedNum}}</p>
    </div>
<script>
  var vm = new Vue({
            el:"#app",
            data:{
                num:1,
            },
            computed:{
                computedNum(){
                    console.log("Calculation properties...")
                    return this.num*2 
                }
            }
        })
</script>
(5) Difference between computed vs Watch
  • The monitoring of watch is only a single monitoring. Each monitoring can only monitor the modification of one variable, and cannot monitor the change of multiple variables at the same time.

The calculated attribute can depend on the changes of multiple data (and only be associated with its dependencies)

  • When you need to perform asynchronous or expensive operations when the data changes, you can only choose to use watch.

  • Calculation attribute is to set a new data for vm through calculated in the instance configuration item, and this new data will have a dependency (an existing data). When the dependency changes, the new data will also change

  • Compared with the method, it has higher performance, and the calculated attributes are cached based on their dependencies. A computed property is re evaluated only when its related dependencies change. In contrast, whenever a re rendering is triggered, the calling method will always execute the function again.

  • Compared with watch, it is simpler to write and more logical. Watch is generally used to perform some actions according to the change of data, but it doesn't matter what these actions are doing, and the calculation attribute is more targeted to change another data according to the change of data

  • The calculation property also has getter and setter. The default is getter. Setting setter can do other things when the calculation property data is changed, which is equivalent to the calculation property of watch

     <div id="app">
            <p>{{fullName}}</p>
            <input type="text" v-model="fullName">
        </div>
        <script>
            new Vue({
                el:"#app",
                data:{
                    firstName:"zhang",
                    lastName:"san"
                },
                computed:{
                    fullName: {
                        get: function () {
                            return this.firstName + ' ' + this.lastName
                        },
                        set: function (newValue) {
                            var names = newValue.split(' ')
                            this.firstName = names[0]
                            this.lastName = names[names.length - 1]
                        }
                    }
                }
            })
    
        </script>
    

Tags: Vue

Posted by msing on Tue, 24 May 2022 04:56:29 +0300