DIV CSS 佈局教程網

Vue.js 計算屬性 computed 入門教學
編輯:關於JavaScript     

計算屬性適合用來描述「某個值依賴其他值」的情境。當依賴資料改變時,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 的差異

$watch 適合觀察資料變化並執行副作用;computed 則適合用來計算衍生值。

var vm = new Vue({
  data: {
    firstName: 'Foo',
    lastName: 'Bar'
  },
  computed: {
    fullName: function() {
      return this.firstName + ' ' + this.lastName;
    }
  }
});

setter

如果需要讓計算屬性可寫,可以加入 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 中非常實用的功能,能讓資料流更清楚,也能減少重複的監聽程式碼。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved