VUE-计算属性
computed/methods两种方式的最终结果确实是完全相同的。然而,不同的是计算属性是基于它们的依赖进行缓存的。计算属性只有在它的相关依赖发生改变时才会重新求值。这就意味着只要 message
还没有发生改变,多次访问 reversedMessage
计算属性会立即返回之前的计算结果,而不必再次执行函数。
computed/methods
<!-- 计算属性computed/methods --> <div style="height: 250px;background: #CCC;margin: 5px;"> <div style="font-size: 20px;"> v0.计算属性computed/methods</div> <hr /> <div> <div> <p>{{msg}}</p> </div> <div> <p>反转字符串:{{reverseMsg}}</p> </div> <div> <p>反转字符串:{{reverseMsg1()}}</p> </div> <div> <p>Setter/Getter:{{fullName}}</p> </div> </div> </div> |
<!-- 计算属性computed/methods --> <script> var vm = new Vue({ el: "#appVue", data: { msg: "ABCDEFG", msg1: "abcdefg", chPart: "Key", digPart: "123456", }, computed: { reverseMsg: function() { return this.msg.split('').reverse().join('') }, fullName: { get: function() { return this.chPart + this.digPart; }, set: function(newVar) { this.chPart = newVar; this.digPart = newVar; } } }, methods: { reverseMsg1: function() { return this.msg1.split('').reverse().join('') } } }) console.log(vm.reverseMsg); vm.msg = "AAABBB"; console.log(vm.reverseMsg); vm.fullName = "Null"; </script> |
<!DOCTYPE html> <html style="height: 100%;"> <head> <meta charset="UTF-8"> <script type="text/javascript" src="../lib/vue.v2.5.12.js"></script> <title>v-xxx</title> </head> <body style="height: 100%;"> <style> .style0 { font-size: 25px; color: green; } .style1 { background: gold; } </style> <!-- VUE-计算属性 REF: http://www.runoob.com/vue2/vue-computed.html https://cn.vuejs.org/v2/guide/computed.html --> <div id="appVue"> <!-- 计算属性computed/methods --> <div style="height: 250px;background: #CCC;margin: 5px;"> <div style="font-size: 20px;"> v0.计算属性computed/methods</div> <hr /> <div> <div> <p>{{msg}}</p> </div> <div> <p>反转字符串:{{reverseMsg}}</p> </div> <div> <p>反转字符串:{{reverseMsg1()}}</p> </div> <div> <p>Setter/Getter:{{fullName}}</p> </div> </div> </div> </div> <script> var vm = new Vue({ el: "#appVue", data: { msg: "ABCDEFG", msg1: "abcdefg", chPart: "Key", digPart: "123456", }, computed: { reverseMsg: function() { return this.msg.split('').reverse().join('') }, fullName: { get: function() { return this.chPart + this.digPart; }, set: function(newVar) { this.chPart = newVar; this.digPart = newVar; } } }, methods: { reverseMsg1: function() { return this.msg1.split('').reverse().join('') } } }) console.log(vm.reverseMsg); vm.msg = "AAABBB"; console.log(vm.reverseMsg); vm.fullName = "Null"; </script> </body> </html>
REF:
http://www.runoob.com/vue2/vue-computed.html
https://cn.vuejs.org/v2/guide/computed.html