Vue3 calculation Properties
Calculation attribute keywords: computed
.
Computational attributes are useful when dealing with some complex logic.
Take a look at the following example of reversing a string:
Example 1
<divid="app">{{ message.split('').reverse().join('') }}</div>
In example 1, the template becomes very complex and not easy to understand.
Next, let’s take a look at an example that uses calculated properties:
Example 2
<!DOCTYPEhtml><html><head><metacharset="utf-8"><title>Vue Test Example -
Rookie Tutorial(runoob.com)</title><scriptsrc="https://unpkg.com/vue@next"></script></head><body><divid="app"><p>Original String:
{{ message }}</p><p>Invert string after calculation: {{ reversedMessage
}}</p></div><script>const app = { data() { return { message: 'RUNOOB!!'
} }, computed: { // Calculating attributes getter reversedMessage: function () { //
\`this\` Point to vm instance return this.message.split('').reverse().join('') }
} } Vue.createApp(app).mount('#app')</script>
A calculation property is declared in example 2 reversedMessage
.
The function provided will be used as a property vm.reversedMessage
of getter
.
vm.reversedMessage
depend on vm.message
in vm.message
when there is a change vm.reversedMessage
will also be updated.
Computed vs methods
We can use methods
to replace computed
both of them are the same in effect, but computed
is based on its dependency cache and will only be re-valued when the dependency changes. And use methods
when re-rendering, the function is always called again to execute
Example 3
methods:{reversedMessage2:function(){returnthis.message.split('').reverse().join('')}}
It can be said to use computed
performance will be better, but if you don’t want caching, you can use the methods
property.
Computed setter
computed
property defaults to only getter
but you can also provide one when needed setter
:
Example 4
varvm=newVue({el:'#app',data:{name:'Google',url:'http://www.google.com'},computed:{site:{//getterget:function(){returnthis.name+''+this.url},//setterset:function(newValue){varnames=newValue.split('')this.name=names[0]this.url=names[names.length-1]}}}})//call
setter, vm.name and vm.url will also be updated accordingly with vm. site='Rookie Tutorial'
http://www.runoob.com';document.write('name:'+vm.name);document.write('<br>');document.write('url:'+vm.url);
Judging from the running results of the instance, when running vm.site = ‘rookie tutorial http://www.runoob.com’; setter
will be called. vm.name
and vm.url
will also be updated accordingly.