六、計算屬性的使用(computed)
阿新 • • 發佈:2022-03-30
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>