Vue中methods、computed和watch屬性聯繫及區別

methods屬性

當我們在Vue中想要調用函數或者方法時,可以在methods中調用方法,如下:

<template>
  <div>
        <h1>methods屬性</h1>
        {{ getFullname() }}
        {{ getFullname() }}
        {{ getFullname() }}
        {{ getFullname() }}
  </div>
</template>

<script>
export default {
  name: "Methods",
  data() {
    return {
        firstname:'三',
        lastname:'張'
    };
  },
  methods: {
      getFullname:function() {
          console.log('1')   // 4個1     
          return this.lastname + this.firstname
      }
  }
};
</script>

執行上述過程可以在瀏覽器頁面中顯示四次‘張三’,由於methods沒有緩存,所以控制檯打印出4個1。同時,method中 getFullname是方法名,調用時需要在後面加括號。

computed屬性

對於上述methods方法,如果出現大量的同一函數重複調用,會消耗大量計算資源,此時我們需要利用computed屬性,如下:

<template>
  <div>
        <h1>computed屬性</h1>
        {{ getFullname }}
        {{ getFullname }}
        {{ getFullname }}
        {{ getFullname }}
        {{ getFullname }}
  </div>
</template>

<script>
export default {
  name: "Methods",
  data() {
    return {
        firstname:'四',
        lastname:'李'
    };
  },
  computed: {
      getFullname:function() {
          console.log('1')  // 1個1,因爲有緩存
          return this.lastname + this.firstname
      }
  }
};
</script>

執行上述過程可以在瀏覽器頁面中同樣顯示四次‘李四’,但computed有緩存,上述過程是同一函數調用了多次,所以控制檯只打印出1個1。同時,computed中 getFullname是一種屬性,調用時無需添加括號即可執行。

補充:
其實,每個計算屬性都包含一個get和一個set屬性。對於上述過程,我們只是使用了get來讀取,當然不指定的話默認也是get。在某些情況下,也會用到set方法(不常用,瞭解即可)。

<template>
  <div>
        <h1>computed屬性</h1>
        {{ getFullname }}
        {{ getFullname }}
        {{ getFullname }}
        {{ getFullname }}
        {{ getFullname }}
  </div>
</template>

<script>
export default {
  name: "Methods",
  data() {
    return {
        firstname:'四',
        lastname:'李'
    };
  },
  computed: {
      getFullname:{
        set:function(newValue){
            console.log(newValue)
        },
        get:function(){
            return this.lastname + this.firstname // 默認調用
        }
      }
  }
};
</script>

當我們對組件中的getFullname進行重新賦值後,會調用set屬性,當然一般不是很常用。

watch屬性

watch屬性用來監聽綁定數據內容變化,如下:

<template>
  <div class=''>
      <h1>watch屬性</h1>
      <input type="text" v-model='content'>
  </div>
</template>

<script>
export default {
  name: '',
  data(){
    return {
        content:'123'
    }
  },
  watch:{
      content:function(newValue,oldValue){
          console.log('oldValue:' + oldValue)
          console.log('newValue:' + newValue)
      }
  }
}
</script>

輸入框內容和data中的content綁定,當輸入框內容發生變化時,就會調用watch屬性。
注意:watch使用時,屬性名字與數據名字需一致(如上述代碼中的content)。

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