For any complex logic, you should use computational properties, the official website says.
computed:
Directly use the name of the calculated property as the variable name.
Calculated properties are cached based on their dependencies. A computed property is re evaluated only if its associated dependency changes.
That is, when the value of the value to be calculated in computed changes, the calculation attribute recalculation will be triggered, which can improve the performance.methods:
The difference with computed is that when there are other elements on the page that are not dependent within the calculated attribute that need to be re rendered, the calculated attribute will first see whether the dependent value changes. If not, the method written in methods will not be re calculated. When there is a need to render, all the methods in methods will be executed once. It's less efficient.
In the demo, you can enter values in the other input box. Only methods will be printed out, indicating another execution.
- watch:
Listen for the change of the value of two variables. After any change, the calculation will be carried out. The effect is the same as that of the calculated attribute, but the code is a bit troublesome.
**set method for Calculating Properties
The default calculation property is the get method. To write the set method, for example, total0 in the example.
The test method is as follows: assign value to total0:
vm.total0='2'
After that, the set method of total0 will be triggered;
If total is assigned, an error will be reported:
[Vue warn]: Computed property "total" was assigned to but it has no setter.
Demo:
<div id="app">
<input v-model="one" /> +
<input v-model="two" />
<div>computed reslut = {{total}}</div>
<div>computed set reslut = {{total0}}</div>
<div>methods reslut = {{total2()}}</div>
<div>watch reslut = {{total3}}</div>
<div>other:<input v-model="other"/></div>
</div>
<script>
var vm = new Vue({
el:'#app',
data:{
one:'',
two:'',
other:'',
total3:''
},
computed:{
//Default get method
total:function(){
console.log('computed');
return this.one+this.two;
},
//set, get method
total0:{
get:function(){
console.log('computed get');
return this.one+this.two;
},
set : function (v){
console.log('computed set');
this.one = 'abc';
}
}
},
methods:{
total2:function(){
console.log('methods');
return this.one+this.two;
}
},
watch:{
one:function(v){
this.total3 = v + this.two;
console.log('watch one');
},
two:function(v){
this.total3 = this.one + v;
console.log('watch two');
}
}
});
</script>
Input in the order of 1, 2 and 3, and the execution result is as follows: