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 场景:

1、自适应浏览器(监听浏览器宽高、如果有变化就存在localStorage里面去,或者有变化就通知其他组件改变化)

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 }))
  }
}

2、监控路由对象

new Vue({
        el: '#app',
        router: router, //开启路由对象
        watch: {
          '$route': function(newroute, oldroute) {
            console.log(newroute, oldroute);
            //可以在这个函数中获取到当前的路由规则字符串是什么
            //那么就可以针对一些特定的页面做一些特定的处理
       }
    }
 })

computed 场景:

1、作为过滤器:展开更多

<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;
    }
  }
}
}

2、作为过滤器:tab切换

<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
    }
  }
}

  

原文地址:https://www.cnblogs.com/sayidf/p/9962367.html