Vue.js Computed Properties
Computed property keyword: computed.
Computed properties are very useful when handling complex logic.
You can look at the following example of reversing a string:
Example 1
<div id="app">{{ message.split('').reverse().join('') }}
div
Try it »
In Example 1 the template becomes very complex and hard to read and understand.
Next, let's look at an example that uses computed properties:
Example 2
<div id="app">
<p>Original string: {{ message }}
p
<
p
Reversed string: {{ reversedMessage }}
p
div
<
script
var vm = new Vue({ el: '#app', data: { message: 'Runoob!' }, computed: { // getter of the computed property reversedMessage: function () { // this points to the vm instance return this.message.split('').reverse().join('') } } })
script
Try it »
Example 2 declares a computed property reversedMessage.
The provided function is used as the getter for the property vm.reversedMessage.
vm.reversedMessage depends on vm.message; when vm.message changes, vm.reversedMessage also updates.
computed vs methods
We can use methods instead of computed; the effect is the same in both cases, but computed is based on dependency caching and only re-evaluates when its related dependencies change. With methods, the function is always re-invoked on re-render.
Example 3
methods
:
{
reversedMessage2
:
function
(
)
{
return
this
.
message
.
split
(
'
'
)
.
reverse
(
)
.
join
(
'
'
)
}
}
Try it »
It can be said that using computed has better performance, but if you don't want caching, you can use the methods property.
computed setter
A computed property has only a getter by default, but you can also provide a setter when needed:
Example 4
var
vm
=
new
Vue
(
{
el
:
'
#app
'
,
data
:
{
name
:
'
'
,
url
:
'
http://www.google.com
'
}
,
computed
:
{
site
:
{
//
getter
get
:
function
(
)
{
return
this
.
name
'
'
this
.
url
}
,
//
setter
set
:
function
(
newValue
)
{
var
names
=
newValue
.
split
(
'
'
)
this
.
name
=
names
[
0
]
this
.
url
=
names
[
names
.
length
1
]
}
}
}
}
)
//
Calling the setter, vm.name and vm.url are also updated accordingly
vm
.
site
=
'
Runoob Tutorial http://www.runoob.com
'
;
document
.
write
(
'
name:
'
vm
.
name
)
;
document
.
write
(
'
'
)
;
document
.
write
(
'
url:
'
vm
.
url
)
;
Try it »
Judging from the running result, when running vm.site = 'Runoob Tutorial http://www.runoob.com';, the setter is called and vm.name and vm.url are updated accordingly.
