计算属性computed & 监听属性watch
computed
我们希望一个变量是经过某种计算然后输出,而不是直接输出的时候,可以使用到计算属性
vue
<div>{{ total }}</div>
computed: {
total() {
return this.a + this.b
}
}1
2
3
4
5
6
7
2
3
4
5
6
7
watch
watch可以监听对象,也可以监听对象中的某个属性
当需要在数据变化时执行异步或开销较大的操作时,使用监听器是最有用的
js
watch: {
a(newVal, oldVal) {
this.total = this.a + this.b
},
b(newVal, oldVal) {
this.total = this.a + this.b
},
// obj() {
// // 普通监听形式,只能监听到引用数据类型引用地址的改变
// console.log('watch', this.obj);
// },
obj: {
handler(newVal, oldVal) {
console.log(newVal);
console.log(oldVal);
},
deep: true
}
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
watch 和 computed 的区别
computed的get必须有返回值(return),而watchreturn可有可无computed支持缓存,只有依赖的数据发生改变,才会重新进行计算,而watch不支持缓存,数据发生改变,会直接触发相应的操作computed可以自定义名称,而watch只能监听props和data里面名称相同的属性computed适用于复杂的运算,而watch适合一些消耗性功能,比如Ajaxcomputed不支持异步,当computed内有异步操作是无效,无法监听数据的变化,而watch支持异步computed属性值会默认走缓存,计算属性是基于它们的响应式依赖进行缓存的,也就是基于data中声明过或者父组件传递的props中的数据通过计算得到的值,而watch监听的函数接受两个参数,第一个是最新的值,第二个是输入之前的值- 如果一个属性是由其他属性计算而来的,这个属性
依赖其他属性,多对一或者一对一,一般用computed;当一个属性发生变化时,需要执行对应的操作,一对多,一般用watch