Note: This content is excerpted from “Vue.js Combat” by Liang Hao.
1. Use computed properties when encountering complex logic.
1 <div class="app1"> 2 {{reversedText}} 3 </div> 45 var app1=new Vue({6 el:'.app1', 7 data:{8 text:'123,456' 9}, 10 computed:{ 11 reversedText:function(){ 12 return this.text.split(',').reverse().join(','); 13} 14} 15});Copy the code
All computed attributes are written as functions in the computed option in the Vue instance, which ultimately returns the computed result.
2. Each computed property contains a getter and a setter, which are triggered when manually modifying the value of a computer property as if it were modifying ordinary data.
1 <div class="app3"> 2 </div> 4 5 var app3=new Vue({6 el:'.app3', 7 data:{8 firstName:'Jack', 9 lastName:'Greeen' 10 }, 11 computed:{ 12 fullName:{ 13 get:function(){ 14 return this.firstName+' '+this.lastName; 15 }, 16 set:function(newValue){ 17 var names=newValue.split(' '); 18 this.firstName=names[0]; 19 this.lastName=names[names.length-1]; 20} 21} 22} 23}); 24 app3.fullName="Nancy Chen";Copy the code
Most of the time, we only use the default getter to read a calculated property. Setters are rarely used in business. Therefore, when declaring a calculated property, you can use the default notation instead of declaring both getters and setters.
Tips: One is that computed properties can depend on other computed properties. Second, the calculated attributes can not only rely on the data of the current Vue instance, but also rely on the data of other instances.
3. Calculate the property cache
You may find that calling methods works just as well as evaluating properties.
1 <div class="app4"> 2 <! -- Notice that reversedText is the method, ReversedText () {{reversedText()}} 4 </div> 56 var app4=new Vue({7 el:'.app4', 8 data:{9 text:'123,4567' 10}, 11 methods:{12 reversedText:function(){13 return this.text.split(',').reverse().join(','); 15} 16} 17})Copy the code
Instead of using computed attributes, a method defined in methods achieves the same effect, and even accepts parameters, making it more flexible to use. Why count attributes? The reason is that the calculated property is based on its dependency cache. A calculated property is reevaluated only when the data on which it depends changes, so as long as text remains unchanged, the calculated property is not updated. Methods, on the other hand, will be called as soon as it is rerendered, and therefore the function will be executed.
Which one to use depends on whether you need caching or not.
Note: This content is excerpted from “Vue.js Combat” by Liang Hao.