Vue Computed Properties
Computed properties are dependent on other characteristics, just like data properties.
Computed properties are constructed similarly to methods, but they don’t take any arguments as input.
Computed properties are called upon when something occurs, like in the case of event handling, are updated automatically when a dependence changes.
Computed properties are employed when producing output that is dependent on another output.
Computed Properties are Dynamic
The primary benefit of a calculated property is its dynamic nature, as it varies based on many factors such as the value of one or more data characteristics.
The final configuration option we will learn about for the Vue instance is computed properties. ‘Data’ and’methods’ are the first two configuration options we have already examined.
Computed properties have a reserved name in the Vue instance, “computed,” much like “data” and “methods.”
Syntax
const app = Vue.createApp({
data() {
...
},
computed: {
...
},
methods: {
...
}
})
Computed Property 'yes' or 'no'
Consider the scenario where we need a form to add goods to a shopping list and indicate whether or not each item is new. We could add a ‘true’ or ‘false’ response when the checkbox gets checked, like we have done in an example before:
Example
To ensure that the text reflects the status, a dynamic input element is created.
{{ chbxVal }}
data() {
return {
chbxVal: false
}
}
Instead of responding with “true” or “false,” people will most likely respond with “yes” or “no” if you ask them if something is essential. Therefore, rather than using “true” or “false” as the checkbox’s feedback, we should use “yes” or “no” to make our form more intuitive and more in line with everyday English.
And guess what? A calculated property is the ideal instrument to assist us in doing that.
Example
We can now alter the text feedback that appears to the user when the checkbox is toggled on and off thanks to a computed parameter called “isImportant.”
{{ isImportant }}
data() {
return {
chbxVal: false
}
},
computed: {
isImportant() {
if(this.chbxVal){
return 'yes'
}
else {
return 'no'
}
}
Computed Properties vs. Methods
Although they are both expressed as functions, computed properties and methods are not the same:
- When a dependency changes, computed properties automatically update, but methods continue to run when called from HTML.
- Although computed properties are dynamic, they are used in the same manner as data properties.