Vue learning ---computed Compute properties
1. When writing computed You should pay attention to
-
All computational properties , Must be defined in computed Properties of the ;
-
Calculation properties are defined , To be defined in the form of a method , And defined in the form of a method , Method must have a return value , Because the final result of using calculated attributes is the returned value ;
-
The calculated attribute will eventually become the current Vue Properties of an instance object ;
2.computed Two forms of attributes
- 2.1 Calculation properties in the form of functions
var vm = new Vue({
data: { a: 1 },
computed: {
// This form of calculation property can only read
property1: function () {
return this.a * 2
}
// Abbreviation form
property1(){
return this.a * 2
}
}
})
vm.property1 // => 4
Copy code
Be careful : Here is a small detail that can easily be ignored
If you use... For a calculated attribute Arrow function
, be this Does not point to an instance of this component , However, you can still access its instance as the first parameter of the calculated property function .
var app = new Vue({
data{ a = 2 },
computed:{
arrowFun:(vm) => {
return vm.a *= 2
}
}
})
vm.arrowFun // 4
Copy code
- 2.2 Calculated properties in object form
var vm = new Vue({
data: { a: 1 },
computed: {
// The calculated properties in the form of objects are readable and writable
property2: {
get: function () {
return this.a + 1
},
// val The value of is when the calculation property changes , The value assigned to this calculated property
set: function (val) {
this.a = val - 1
}
}
}
})
vm.property2 // => 2
vm.propert2 = 3
vm.a // => 2
Copy code
3. Use computed The benefits of attributes
-
benefits 1: Realize the reuse of code ;
-
benefits 2: As long as the dependent data source in the calculation attribute changes , The calculated property will be re evaluated ;