Vue computed和watch的區(qū)別

computed : 計(jì)算屬性

重點(diǎn)是得到一個(gè)數(shù)據(jù)

<template>
  <div>{{name}}</div>
<!--使用時(shí)不需要加括號(hào)-->
</template>
<script>
export default{
    data() {
        return {
            firstName: '小花',
            lastName: "王"
        }
    },
    computed: {
        name() {
            return this.firstName + '' + this.lastName
        }
    }
}
</script>

使用時(shí)不需要加括號(hào)
它會(huì)將計(jì)算的結(jié)果自動(dòng)緩存
只有在依賴屬性改變后才會(huì)執(zhí)行

watch : 監(jiān)聽(tīng)

重點(diǎn)是調(diào)用一個(gè)函數(shù)

<template>
  <div id="app">
    <div>最高分是{{highest}}</div>
    <span>作弊按鈕</span>
    <button @click="add(index)" v-for="(course,index) in test" :key = "index">{{index}}加十分</button>
  </div>
</template>

<script>

export default {
    data() {
        return {
            test:{
                語(yǔ)文: 80,
                數(shù)學(xué): 90,
                英語(yǔ): 100
            }
        }
    },
    computed: {
        highest() {
          const {test:{語(yǔ)文,數(shù)學(xué),英語(yǔ)}} = this
          return Math.max(語(yǔ)文,數(shù)學(xué),英語(yǔ))
        }
    },
   watch:{
      test:{
        handler(){
          const test = this.test
          for(let i in test){
            if(test[i] > 150){
              alert(`${i}超過(guò)最高分啦,你太貪了`)
            }
          }
        },
        immediate: true,
        deep: true
      }
   },
   methods:{
     add(index){
       this.test[index]+=10
     },
   }
};
</script>

在上面的例子中,我對(duì)test對(duì)象進(jìn)行了監(jiān)聽(tīng),在加分超過(guò)最高分的時(shí)候批評(píng)貪心的同學(xué)
可以看到監(jiān)聽(tīng)有兩個(gè)參數(shù):

  1. immediate:是否在第一次渲染的時(shí)候執(zhí)行函數(shù)
  2. deep:是否要監(jiān)聽(tīng)對(duì)象里面屬性的變化

當(dāng)相關(guān)數(shù)據(jù)變化了就執(zhí)行回調(diào)函數(shù)
在這個(gè)例子里就是,當(dāng)test對(duì)象或者test對(duì)象里的屬性變化時(shí)就會(huì)執(zhí)行handler

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

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

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