標籤:this com 改變 多次 names new blog sage get
一、使用原因 1、模板中運算式很便利,但實際上只適用於簡單的運算,不適宜放入太多邏輯運算,例如:
<div id="example">{{ message.split(‘‘).reverse().join(‘‘) }}</div> 所以: 任何複雜邏輯,你都應當使用計算屬性 二、使用方法
<div id="app"> 你好{{ ComMessage }} <p>{{ ComMsg() }}</p></div> var vm = new Vue({ el: ‘#app‘, data: { message: ‘hello world‘ }, computed: { ComMessage: function(){ return this.message.split(‘‘).reverse().join(‘‘); //this 指向vm執行個體 } }, method: { ComMsg: function(){ return this.message.split(‘‘).reverse().join(‘‘); //this 指向vm執行個體 } }}); 三、計算屬性 VS 函數方法methods 1、同:如上例子,結果都是一樣 2、異:計算屬效能基於它們的依賴進行緩衝, 計算屬性只有在它的相關依賴發生改變時才會重新求值。這就意味著只要 message 還沒有發生改變,多次訪問 reversedMessage 計算屬性會立即返回之前的計算結 果,而不必再次執行函數。
//意味著下面的計算屬性將不再更新,因為 Date.now() 不是響應式依賴:computed: { now: function () { return Date.now() }} 3、綜上,使用計算屬性還是methods,取決於是否希望有緩衝 四、computed屬性 VS watch屬性
<div id="demo">{{ fullName }}</div> ======================================================var vm = new Vue({ el: ‘#demo‘, data: { firstName: ‘Foo‘, lastName: ‘Bar‘, fullName: ‘Foo Bar‘ }, watch: { firstName: function(val) { this.fullName = val + ‘ ‘ + this.lastName }, lastName: function(val) { this.fullName = this.firstName + ‘ ‘ + val } }}) =======================================================var vm = new Vue({ el: ‘#demo‘, data: { firstName: ‘Foo‘, lastName: ‘Bar‘ }, computed: { fullName: function() { return this.firstName + ‘ ‘ + this.lastName } }}) 五 、setter 計算屬性預設只有 getter ,不過在需要時你也可以提供一個 setter :
// ...computed: { fullName: { // getter get: function() { return this.firstName + ‘ ‘ + this.lastName }, // setter set: function(newValue) { var names = newValue.split(‘ ‘) this.firstName = names[0] this.lastName = names[names.length - 1] } } } // ... 六、Watchers 當你想要在資料變化響應時,執行非同步作業或開銷較大的操作,很有用。
Vuejs --04 計算屬性