Vuejs --04 計算屬性

來源:互聯網
上載者:User

標籤: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 計算屬性

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.