可以通過三種方法實現(xiàn)屬性的運算:computed屬性专普、method和watch(偵聽器)悯衬,如果一個功能可以通過computed屬性和watch實現(xiàn),選用computed屬性是最簡單的檀夹。
watch: {
firstName: function(){
console.log("計算了一次");
this.fullName = this.firstName + " " + this.lastName;
},
lastName: function(){
console.log("計算了一次");
this.fullName = this.firstName + " " + this.lastName;
}
}
// fullName方法甚亭,沒有緩存,頁面只要重新渲染击胜,這個函數(shù)就會重新執(zhí)行一次
// methods: {
// fullName: function () {
// return this.firstName + " " + this.lastName;
// }
// },
// 計算屬性,計算屬性有緩存的概念
// computed:{
// fullName: function () {
// console.log("計算了一次");
// return this.firstName + " " + this.lastName;
// }
// }
})
其中computed有g(shù)etter setter屬性亏狰,當改變了firstName和lastName時,set起作用偶摔,同時會重新計算fullName的值暇唾,頁面中的fullName也會發(fā)生變化