1: Why computational attributes?

What was the original intention? – Expressions in templates are very handy, but they are designed for simple calculations. Putting too much logic into a template can make it too heavy and difficult to maintain

– It is not simple declarative logic in this template, it must take a while to understand, so you should use computed properties for any complex logic

– Here we declare a calculated property reversedMessage. The function we provide will be used as the getter for the property Vm.reversedMessage: – You can open the browser console and modify the vm. message in the example – trigger the set as written in HTML

<div class="app"> <p>{{message}}</p> <p>reverse{{reverseMessage}}</p> </div> <script> var vm = new Vue({ el: "#app", data: {message: 'hello'}, computed: {// Reverse reverseMessage: function () { return this.message.split('').reverse().join('') } } }) </script>Copy the code

2. Calculate properties vs. methods

– You can achieve the same effect by calling methods in expressions

– The end result is exactly the same. – The difference, however, is that computed attributes are cached based on their reactive dependencies. They are reevaluated only when the associated reactive dependencies change. This means that as long as nessage has not changed, multiple visits to the reversedMessage calculated property will immediately return the result of the previous calculation without having to execute the function again. (As long as message remains unchanged, I will never move again. If I move, I lose.)

<div class="app"> <p>{{message}}</p> <p>reverse{{reverseMessage}}</p> <p>reverse{{getMessage}}</p> </div> <script> var Vm = new Vue({el: "#app", data: {message: 'hello'}, // Compute attributes computed: {// Reverse reverseMessage: function () { return this.message.split('').reverse().join('') } }, // methods:{getMessage(){return this.message.split('').reverse().join('')}}}) </script>Copy the code

Evaluate the set of attributes

<div class="app"> <p>{{message}}</p> <p>reverse{{reverseMessage}}</p> <p>reverse{{getMessage}}</p> </div> <script> var Vm = new Vue({el: "#app", data: {message: 'hello'}, // Compute attributes computed: {// abbreviation // reverseMessage: // Return this.message.split('').reverse().join('') //} // There is a big reverseMessage: {get: Function () {return this.message.split('').reverse().join('')}, Set :function(val){console.log(val); }}}, / / the method the methods: {getMessage () {return this. The message. The split (' '). The reverse () join (' ')}}}) < / script >Copy the code