1.computed
computed:计算属性
要用得属性不存在,要通过已有得属性计算来(不存在data里面)
eg:
data() {
return {
isHot: true,
}
},
computed: {
info() {
return this.isHot ? '炎热' : '寒冷'
},
},
2.methods和computed相比
和methods相比,两者都可以实现相同的功能,但是计算属性可以进行缓存,如果多次使用,计算属性只会调用一次,效率更高。
3.watch
watch:监视属性
监视属性的变化,发生变化则进行相关操作。
1.监视的属性必须存在,可以是data里面,也可以是计算属性
2.监视属性总的有两种写法,
①一个是写vue对象里面;watch:{ }
②一个则是通过 vm.$watch(’ 属性名’, {watch里面的函数eg:handler等 } )
3.watch里面有
①函数 handler(newValue,oldValue){ }; 【新的值,旧的值】
②immediate ,默认是false, 设置true,表示初始化时让handler调用一次
③deep:true ,开启深度监视;
eg1:
watch: {
isHot: {
handler(newValue, oldValue) {
console.log('isHot', newValue, oldValue);
}
},
}
eg2:
简写:【当涉及到只有handler函数的时候】
watch: {
isHot(newValue, oldValue) {
console.log('isHot', newValue, oldValue);
}
},
4.computed和watch相比
1.watch不会进行缓存
2.computed能完成的。watch都能完成,而watch能完成的,computed不一定能完成,watch能写一些需要异步操作的,eg:定时器,网络请求【因为computed是通过return来返回值】
3.computed是 多个数据影响一个(多对一);watch则是一对多,一个数据发生变化,引发相应的操作,从而影响多个数据
eg3:
进行异步操作
watch: {
firstName(n, o) {
this.fullName = n + '-' + this.lastName
},
lastName(n, o) {
this.fullName = n + '-' + this.firstName
},
fullName(n, o) {
setTimeout(() => {
console.log(this, 'this指向是vm');
this.fullName = n
}, 1000)
}
}