Computed properties are like data properties, except they depend on other properties.
Computed properties are written like methods, but they do not accept any input arguments.
Computed properties are updated automatically when a dependency changes, while methods are called on when something happens, like with event handling for example.
Computed properties are used when outputting something that depends on something else.
The big advantage with a computed property is that it is dynamic, meaning it changes depending on for example the value of one or more data properties.
Computed properties is the third configuration option in the Vue instance that we will learn. The first two configuration options we have already looked at are 'data' and 'methods'.
As with 'data' and 'methods' computed properties also has a reserved name in the Vue instance: 'computed'.
const app = Vue.createApp({
data() {
...
},
computed: {
...
},
methods: {
...
}
})
Let's say we want a form to create items in a shopping list, and we want to mark if a new item is important or not. We could add a 'true' or 'false' feedback when the checkbox gets checked, like we have done in an example before:
An input element is made dynamic so that the text reflects the status.
<input type="checkbox" v-model="chbxVal"> {{ chbxVal }}
data() {
return {
chbxVal: false
}
}
Try it Yourself »
However, if you you ask someone if something is important, they will most likely answer 'yes' or 'no' instead of 'true' or 'false'. So to make our form more fitting with normal language (more intuitive) we should have 'yes' or 'no' as feedback on the checkbox instead of 'true' or 'false'.
And guess what, a computed property is a perfect tool to help us with that.
With a computed property 'isImportant' we can now customize the text feedback to the user when the checkbox is toggled on and off.
<input type="checkbox" v-model="chbxVal"> {{ isImportant }}
data() {
return {
chbxVal: false
}
},
computed: {
isImportant() {
if(this.chbxVal){
return 'yes'
}
else {
return 'no'
}
}
Try it Yourself »
Computed properties and methods are both written as functions, but they are different:
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!