Skip to content

vue中watch和computed区别 #6

Description

@nokelong

一、computed
vue中的computed是计算属性,根据依赖的属性动态显示新的计算结果,,该计算结果会被缓存起来。computed的值在getter执行后是会被缓存的。如果所依赖的数据发生改变时候, 就会重新调用getter来计算最新的结果。

 data: {
    firstName: 'Foo',
    lastName: 'Bar'
 },
 computed: {
    fullName: function () {
      return this.firstName + ' ' + this.lastName
    }
  }

二、watch
vue中watch是监控侦听器,对data属性监控回调,但数据变化的时候自动触发回调函数,并传入传入newVal和oldVal两个参数。

data(){
    return {
        'first':{
          second:0
        }
    }
},
watch:{
    secondChange:{
        handler(oldVal,newVal){
          console.log(oldVal)
          console.log(newVal)
        },
        deep:true
    }
}

三、watch和computed区别

1、功能上:
computed是计算属性,依赖其它的属性计算所得出最后的值。watch是去监听一个值的变化,然后执行相对应的函数。

2、依赖收集的发生点:
watch 收集依赖的流程是发生在页面渲染之前,computed是在页面渲染时进行取值才会收集依赖。

3、使用上:
computed中的函数必须要用return返回;watch的回调里面会传入监听属性的新旧值,不是必须要用return返回。

4、性能上:
computed中的函数所依赖的属性没有发生变化,则直接从缓存中读取;而watch在每次监听的属性发生变化的时候都会执行回调。

5、使用场景
computed 擅长处理的场景:一个数据受多个数据影响,列如“”购物车商品结算“”;watch擅长处理的场景:一个数据影响多个数据,列如“”搜索框“”。

注: computed 的更新需要“渲染Watcher”的辅助,watch 不需要。

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions