1、计算属性包含getter和setter方法,如下图所示,调用时不用加“()”,但是当我们一般使用时,一般情况下不需要实现set方法,为只读属性
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script src="../Js/vue.min.js"></script> </head> <body> <div id="app"> <span> {{fullName}} </span> </div> <script> const app = new Vue({ el:"#app", data: { firstName: "Kobe", lastName: "Bryant", }, //计算属性一般是 没有set方法,为只读属性 computed: { //完整写法 fullName: { set: function(newValue){ console.log(newValue); const names = newValue.split(" "); this.firstName = names[0]; this.lastName = names[1]; }, get: function(){ return this.firstName + this.lastName ; } } //简便写法 //fullName: function(){ //} } }); </script> </body> </html>
2、计算属性和methods对比,计算属性会将执行结果存放到缓存中,不需要重复的从头开始执行方法,methods需要从头执行,放使用 for 的情况较多时,计算属性可以提供更加优质的效率。
下图为计算属性的一般操作
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script src="../Js/vue.min.js"></script> </head> <body> <div id="app"> <h5> 书的总价格 {{priceSum}} </h5> </div> <script> const app = new Vue({ el : "#app", data:{ books:[ {id: 110 , name: "Unix编程技术" , price: 119}, {id: 120 , name: "书本术1" , price: 119}, {id: 130 , name: "书本术2" , price: 189}, {id: 140 , name: "书本术3" , price: 245}, ] }, computed:{ priceSum:function(){ let result = 0; // for(let i= 0 ; i< this.books.length ; i++){ // result += this.books[i].price; // } // for(let i in this.books){ // result += this.books[i].price; // } for(let book of this.books){ result += book.price; } return result; } } }); </script> </body> </html>