Vue:Computed
lastmod 2021-08-24created 2020-10-154 edits
In vue, use computed properties instead of data for complex logic.
Computed property caching vs methods
You can get the same result by calling a method in the expression.
// 컴포넌트 내부
methods: {
reversedMessage: function () {
return this.message.split('').reverse().join('')
}
}
Instead of a computed property, you can define the same function as a method. As far as the final result goes, the two approaches are identical. The difference is that computed properties are cached based on their dependencies. A computed property only re-runs its function when one of its dependencies changes. That means as long as message has not changed, requesting the computed property reversedMessage multiple times immediately returns the previously computed result without recomputing it.
When it does not update
This also means that a computed property that depends on nothing, like Date.now(), will never update.
computed: {
now: function () {return Date.now()}
}
Simple example
html file:
<div id="example">
<p>원본 메시지: "{{ message }}"</p>
<p>역순으로 표시한 메시지: "{{ reversedMessage }}"</p>
</div>
javascript file:
var vm = new Vue({
el: '#example',
data: {
message: '안녕하세요'
},
computed: {
// 계산된 getter
reversedMessage: function () {
// `this` 는 vm 인스턴스를 가리킵니다.
return this.message.split('').reverse().join('')
}
}
})
Setter function of a computed property
Computed properties have only a getter function by default, but you can create and use a setter function if needed.
// ...
computed: {
fullName: {
// getter
get: function () {
return this.firstName + ' ' + this.lastName
},
// setter
set: function (newValue) {
var names = newValue.split(' ')
this.firstName = names[0]
this.lastName = names[names.length - 1]
}
}
}
// ...
Now when you run vm.fullName = 'John Doe', the setter is called and vm.firstName and vm.lastName are updated accordingly.
Troubleshooting
TypeScript Getter malfunction error
See Vue-class-component#TypeScript Getter malfunction error.