計算屬性setter與getter

在Vue的計算屬性中,默認調用的是getter屬性,而當設置了getter與setter屬性之後,每調用一次計算屬性,就相當於調用一次getter屬性;當計算屬性的值發生變化時,會默認調用setter屬性,進行相應的操作

格式爲:

computed: {
  計算屬性名稱: {
    get: function () {
      get方法
    },
    set: function () {
      set方法
    }
  }
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>計算屬性</title>
</head>
<body>
<div id="app">
  <p>{{menu}}</p>
  <button @click="addDate">日期加1</button>
</div>
<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      year: 2020,
      month: 6,
      day: 20
    },
    methods: {
      addDate: function () {
        this.day++;
        if (this.day > 31) {
          this.day = 1;
          this.month++;
        }
        if (this.month > 12) {
          this.month = 1;
          this.year++;
        }
        this.menu = this.year + "/" + this.month + "/" + this.day;
      }
    },
    computed: {
      menu: {
        get: function () {
          console.log("get方法");
          return +this.year + "/" + this.month + "/" + this.day;
        },
        set: function (date) {
          console.log("set方法");
          const arr = date.split("/");
          this.year = arr[0];
          this.month = arr[1];
          this.day = arr[2];
        }
      }
    }
  })
</script>
</body>
</html>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章