Calculation attribute keyword: calculated
Calculation attribute purpose: used to deal with some complex logical problems.
I believe that many people have encountered the problem of string inversion. Let's demonstrate it with computational properties
Vm.reverse message depends on vm.message. When vm.message is updated, vm.reverse.message is also updated.<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Vue Calculation properties</title> <script src="vue.js"></script> </head> <body> <div id="app"> <p>Original string: {{ message }}</p> <p>Reverse string after calculation: {{ reversedMessage }}</p> </div> <script> var vm = new Vue({ el: '#app', data: { message: 'Runoob!' }, computed: { // getter of calculated property reversedMessage: function () { // `this' points to vm instance return this.message.split('').reverse().join('') } } }) </script> </body> </html>
computed vs methods
In effect, the two are the same, but computed is based on its dependency cache. Only when the relevant dependency changes will the value be retrieved.
With methods, when rendering again, the function will always call and execute again.
I think the computed attribute is easy to use. If there is no caching problem, the method method can also be used.methods: { reversedMessage2: function () { return this.message.split('').reverse().join('') } }
The default attribute of computed is only getter, and setter can be created if necessary
When vm.site = 'ww 10' is running, setter will be called and vm.name and vm.age will be updated accordingly.<body> <div id="app"> <p>{{ site }}</p> </div> <script src="vue.js"></script> <script> var vm = new Vue({ el:'#app', data:{ name:'haha', age:20 }, computed:{ site:{ //getter get:function(){ return this.name + 'This year' +this.age + 'year' }, //setter set: function (newValue) { var names = newValue.split(' ') this.name = names[0] this.url = names[names.length - 1] } } } }) // Call setter, vm.name and vm.url will also be updated accordingly vm.site = 'ww 10';