vue watch和computed的使用場景

watch 監聽某個數據的變化(監聽完調用什麼函數) 一個數據影響多個數據 (好比:瀏覽器自適應、監控路由對象、監控自身屬性變化)瀏覽器

computed 計算後返回新 一個數據受多個數據影響(好比:計算總價格、過濾某些數據)
computed是用來處理你使用watch和methods的時候沒法處理(好比有緩存的時候監聽不了數據變化),或者是處理起來並不太恰當的狀況的,利用computed處理methods存在的重複計算狀況
複製代碼
watch: {
firstName(val) { this.fullName = val + this.lastName }
}

computed: {
fullName() { this.firstName + this.lastName; }
}
複製代碼

 

watch 場景:緩存

一、自適應瀏覽器(監聽瀏覽器寬高、若是有變化就存在localStorage裏面去,或者有變化就通知其餘組件改變化)app

複製代碼
data() {
  return {
    height: ''
  }
},
mounted() {
  const _this = this
  this.height = document.documentElement.clientHeight
  localStorage.setItem('whVal', JSON.stringify({'height': this.height }))
  window.onresize = function temp() {
    _this.height = document.documentElement.clientHeight
  }
},
watch: {
  // 若是發生改變,這個函數就會運行
  height() {
    this.changeFixed(this.width, this.height)
    // eventBus.$emit('onresize', {'height': this.height }) 或者通知其餘組件變化
  }
},
methods: {
  changeFixed(width, height) { // 動態修改樣式
    localStorage.setItem('Layout', JSON.stringify({'height': height }))
  }
}
複製代碼

二、監控路由對象函數

複製代碼
new Vue({
        el: '#app',
        router: router, //開啓路由對象
        watch: {
          '$route': function(newroute, oldroute) {
            console.log(newroute, oldroute);
            //能夠在這個函數中獲取到當前的路由規則字符串是什麼
            //那麼就能夠針對一些特定的頁面作一些特定的處理
       }
    }
 })
複製代碼

 

 

computed 場景:this

一、做爲過濾器:展開更多spa

複製代碼
<li v-for="(item,index) in addressListFilter" :class="{'check':checkIndex == index}" @click="checkIndex=index;selectedAddrId=item._id"></li>
<a @click="expand" v-bind:class="{'open':limit>3}">展開更多</a>

data(){
  return {
    addressList:[],   // 地址列表
    limit:3,   // 限制默認顯示3個地址
  checkIndex:0
  }
},
computed:{
  addressListFilter(){
    return this.addressList.slice(0,this.limit);
  }
},
methods:{
  expand(){  //  點擊more更多
    if(this.limit ==3){
      this.limit = this.addressList.length;
    }else{
      this.limit =3;
    }
  }
}
}
複製代碼

 

二、做爲過濾器:tab切換code

複製代碼
<span v-for="(item,index) in navList" :key="index" @click="type = index" :class="{'active':type===index}">{{item}}</span>
<li v-for="(item,index) in taskListfilter" :key="index">
</li>
data() {
    return {
      navList: ['所有', '實時單', '競價單'],
      type:0,
      taskList:[]
    }
},
computed: {
  taskListfilter() {
    switch (this.type) {
      case 0:return this.taskList
      case 1:return this.taskList.filter(item => item.type === '實時單')
      case 2:return this.taskList.filter(item => item.type === '競價單')
      // default :return this.taskList
    }
  }
}
相關文章
相關標籤/搜索