Vue computed 和watch 的区别

computed和watch的相同点:

        当依赖数据发生改变的时候,自动触发对应的方法。

computed和watch的不同点:

computed是计算属性:

就是和data 里面数据属性一样的使用方式,不用当成函数来调用。

擅长处理的场景:一个数据受多个数据的影响。 例如

当firstName发生改变的时候就会触发fullName ,fullName调用不用当成函数那样用(),

<input v-model="firstName" >
<p>{{fullName }}</p>
computed:{
    fullName:function(){
           return this.firstName+this.lastName
}
}

 watch:类似于监听+事件

                就是监听的某个数据发生了变化后,那么执行相对应的函数。

                擅长处理的场景:一个数据影响多个数据。通过下面的例子就可以看出来。

watch: {
  firstName: function (firstName) { this.fullName = firstName + this.lastName }
}



猜你喜欢

转载自blog.csdn.net/weixin_41436338/article/details/79874470