Computed Properties
Computed properties are a way to derive new data from reactive data; they automatically update when the dependent data changes. In ofa.js, computed properties are special methods defined in the proto object, using JavaScript's get or set keywords.
Features and Advantages
- Caching: The result of a computed property is cached and only recalculated when its dependent data changes
- Reactivity: When dependent data updates, the computed property automatically updates
- Declarative: Dependencies are created declaratively, making the code clearer and easier to understand
get computed property
get computed property is used to derive a new value from reactive data, it does not accept parameters and only returns a value calculated based on other data.
The computed property countDouble value is: {{countDouble}}
Example of Practical Application Scenario
Computed properties are often used to handle complex data transformation logic, such as filtering arrays, formatting displayed text, etc.:
- {{$data}}
set computed properties
Set computed property allows you to modify the underlying data state through assignment operations. It receives a parameter, usually used for reverse-updating the original data that depends on it.
Base value: {{count}}
Double value: {{countDouble}}
Computed Properties vs Methods
Although methods can also achieve similar functions, computed properties have caching characteristics and will only recalculate when their dependent data changes, which makes performance better.
// Using computed properties (recommended) - cached
get fullName() {
return this.firstName + ' ' + this.lastName;
}
// Using methods - executed on each call
fullName() {
return this.firstName + ' ' + this.lastName;
}
Notes
- Avoid Asynchronous Operations: Computed properties should remain synchronous and side-effect-free; asynchronous calls or direct state mutations are prohibited.
- Dependency Tracking: Rely solely on reactive data; otherwise, updates will be unpredictable.
- Error Protection: Circular dependencies or abnormal assignments inside a computed property can cause rendering failures or even infinite loops—set boundary conditions and handle exceptions in advance.
Practical Application Examples
The following is a simple form validation example that demonstrates the practicality of computed properties:
Simple Validation Example
Status: {{statusMessage}}