vue的watch和computed

methods和computed的區別

假設有這樣一個場景,需要拼接data裏的屬性,如果直接{{first+second}},不利於修改;

我們會想到method獲取,但是直接在{{}} 裏放函數表達式,會消耗多餘性能,不建議使用,舉例說明:

假設函數爲getTegeter,如果用函數取值,其他的data屬性修改時會重新render Dom,getTegeter函數會再執行一次,這不是我們希望看到的,

此時,computed的好處就體現了(具體代碼看第二段):

computed定義的函數,只有與他相關的值發生修改時纔會再次觸發,減少了不必要的執行。

<div id="app">
{{getTegether()}}  
<!-- {{first + second}} -->
<div @click="test=!test">{{test}}</div>
</div>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script>
let vm = new Vue({
  el:'#app',
  data:{
    first:'我',
    second:'你',
    test:true
  },
  methods:{
    getTegether(){
      console.log(1)
      return this.first + this.second
    }
  }
})

使用computed的寫法:

<div id="app">
{{getTegether}} 
<div @click="test=!test">{{test}}</div>
</div>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script>
let vm = new Vue({
  el:'#app',
  data:{
    first:'我',
    second:'你',
    test:true
  },
  computed:{
    getTegether(){
      console.log(1)
      return this.first + this.second
    }
  }
})
</script>

computed的原理:

  1. 他是基於Object.defineProperty處理的,裏面有get和set兩個方法,默認觸發get方法,有修改操作時會觸發set
  2. computed會有緩存,如果依賴的數據不發生變化,不會重新執行方法
let vm = new Vue({
  el:'#app',
  data:{
    first:'我',
    second:'你',
    test:true
  },
  computed:{
    getTegether:{
      get(){
        return this.first + this.second
      },
      set(val){
        this.test = val;
      }
    }
  }
})

watch和computed區別

先上一段watch的用法

watch:{
  first:{
    handler(newVal,oldVal){
      setTimeout(()=>{
        this.test = newVal
      },1000)
    },
    imediate:true,//偵聽開始時立即調用
    deep:true//只要屬性發生變化就觸發此函數,不論其被嵌套多深(默認監聽到第一層)
  }
}

watch和computed在處理同步方法時,效果差不多,

處理簡單的事件,異步事件(比如數據變化就發送請求接口)時使用watch;

只是計算一個值的結果,就用computed

animate動畫

<div id="app">
<input type="text" v-model="filter">
<transition-group
  enter-active-class="bounceIn"
  leave-active-class="bounceOut">
  <div class="box animated" v-if="isShow" v-for="(d) in searchData" :key="d.title">
    {{d.title}}
  </div>
</transition-group>
</div>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="../node_modules/velocity-animate/velocity.js"></script>
<script>
let vm = new Vue({
  el:'#app',
  data:{
    isShow:true,
    filter:'',
    dataList:[
      {title:'標題1'},{title:'標題2'},{title:'標題3'}
    ]
  },
  computed:{
    searchData(){
      return this.dataList.filter((item)=>{
        return item.title.includes(this.filter)
      })
    }
  },
})
</script>
<style>
  .box{
    width:100px;height:100px;
    background:#f00;
    color:#fff;
  }
  .bounceIn{
    color:#000;
  }
  .bounceOut{
    color:#ff0;
  }
</style>

 

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