計算屬性適合用來描述「某個值依賴其他值」的情境。當依賴資料改變時,Vue.js 會自動更新計算屬性與畫面。
<div id="example">
a={{ a }}, b={{ b }}
</div>
var vm = new Vue({
el: '#example',
data: {
a: 1
},
computed: {
b: function() {
return this.a + 1;
}
}
});
當 a 改變時,b 也會跟著改變。這讓畫面更新變得聲明式,不需要手動操作 DOM。
$watch 適合觀察資料變化並執行副作用;computed 則適合用來計算衍生值。
var vm = new Vue({
data: {
firstName: 'Foo',
lastName: 'Bar'
},
computed: {
fullName: function() {
return this.firstName + ' ' + this.lastName;
}
}
});
如果需要讓計算屬性可寫,可以加入 setter。
computed: {
fullName: {
get: function() {
return this.firstName + ' ' + this.lastName;
},
set: function(newValue) {
var names = newValue.split(' ');
this.firstName = names[0];
this.lastName = names[names.length - 1];
}
}
}
計算屬性是 Vue.js 中非常實用的功能,能讓資料流更清楚,也能減少重複的監聽程式碼。