computed和watch的區(qū)別

computed 的通過幾個數(shù)據(jù)的變化,來影響一個數(shù)據(jù),支持緩存,不支持異步
watch監(jiān)聽一個數(shù)據(jù)的變化,去影響多個數(shù)據(jù)。不支持緩存,支持異步

// computed :
<template>
  <div>
    <p>{{ reversedMessage }}</p>
  </div>
</template>
 
<script>
export default {
  name: 'test1',
  data () {
    return {
      message: 'hello world',
      number: 1
    }
  },
  computed: {
    // 字符串反轉(zhuǎn)
    reversedMessage () {
      return this.message.split('').reverse().join('') + this.number
    }
  }
}
</script>
//watch:
<template>
  <div>
    <p>{{ this.number }}</p>
  </div>
</template>
 
<script>
export default {
  name: 'test1',
  data () {
    return {
      number: 1
    }
  },
  created () {
    setTimeout(() => {
      this.number = 100
    }, 2000)
  },
  watch: {
    number (newVal, oldVal) {
      console.log('number has changed: ', newVal)
    }
  }
}
</script>

計算屬性computed:
1 支持緩存,只有依賴數(shù)據(jù)發(fā)生改變,才會重新進行計算
2 不支持異步,當computed內(nèi)有異步操作時無效,無法監(jiān)聽數(shù)據(jù)的變化
3 computed 屬性值會默認走緩存,計算屬性是基于它們的響應式依賴進行緩存的,也就是基于data中聲明過或者父組件傳遞的props中的數(shù)據(jù)通過計算得到的值
4 如果一個屬性是由其他屬性計算而來的,這個屬性依賴其他屬性,是一個多對一或者一對一,一般用computed
5 如果computed屬性屬性值是函數(shù),那么默認會走get方法;函數(shù)的返回值就是屬性的屬性值;在computed中的,屬性都有一個get和一個set方法,當數(shù)據(jù)變化時,調(diào)用set方法
偵聽屬性watch:
1 不支持緩存,數(shù)據(jù)變,直接會觸發(fā)相應的操作;
2 watch支持異步,computed不支持異步
3 監(jiān)聽的函數(shù)接收兩個參數(shù),第一個參數(shù)是最新的值;第二個參數(shù)是輸入之前的值;
4 當一個屬性發(fā)生變化時,需要執(zhí)行對應的操作;一對多;
5 監(jiān)聽數(shù)據(jù)必須是data中聲明過或者父組件傳遞過來的props中的數(shù)據(jù),當數(shù)據(jù)變化時,觸發(fā)其他操作,函數(shù)有兩個參數(shù),
  immediate:組件加載立即觸發(fā)回調(diào)函數(shù)執(zhí)行,
  deep: 深度監(jiān)聽,為了發(fā)現(xiàn)對象內(nèi)部值的變化,復雜類型的數(shù)據(jù)時使用,例如數(shù)組中的對象內(nèi)容的改變,注意監(jiān)聽數(shù)組的變動不需要這么做。注意:deep無法監(jiān)聽到數(shù)組的變動和對象的新增,參考vue數(shù)組變異,只有以響應式的方式觸發(fā)才會被監(jiān)聽到。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容