Computed和watch

169次阅读

共计 947 个字符,预计需要花费 3 分钟才能阅读完成。

computed 是计算属性,watch 是侦听器

  • computed 是计算属性,通过其他变量计算得来的另一个属性,

    • 如 fullname 在它所依赖的 firstname 和 lastname 两个变量变化时重新计算自己的值。
    • 另外,computed 具有缓存。计算属性是基于他们的依赖进行缓存的,只有相关依赖发生改变时才会重新求值,意味着如果依赖没变,多次访问计算属性都会立即返回之前的计算结果,而不必每次都执行函数
  • watch 是侦听器,侦听一个特定的值,当该值变化时执行特定函数。
data() {
return {
firstname: '空条',
lastname: '承太郎',
fullname2: '空条承太郎'
}
},
watch: {lastname: function(val) {this.fullname2 = this.firstname + ' ' + val}
}
// this.lasttname = '徐伦'
// console.log(this.fullname2) // 空条徐伦
computed: {fullname: function(val) {return this.firstname + ' ' + this.lastname}
} // 空条承太郎

总结:

1、也就是 computed 是关联多个变量的,只要其中一个变量值改变,都会触发函数;watch 则只依赖一个变量,每次只能对一个变量进行监控。

2、最重要的一点是:watch 是监听 data 里定义的值,而 computed 的计算属性只能在 computed 内,不能在 data 中定义,否则会报错 (重复定义),因为 computed 作为计算属性定义变量并返回对应的结果给这个变量,变量不可被重复定义和赋值。

3、①:computed 中使用箭头函数的话,会导致 this 指向的不是 vueComponent(因为箭头函数没有自己的 this,而是和上一层作用域共享 this,computed 的上一层作用域可能就没有了,所以 this 是 undefined)

②:使用 function() 形式就可以解决,this 指向 vueComponent
③:使用对象的形式,get()、set() 也都指向 vueComponent(例:fullname: {get() {return this.firstname + ‘ ‘ + this.lastname}})

正文完
 0