-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Labels
Description
一、computed和watch的区别
computed特性
- 应用:就是简化tempalte里面{{}}计算和处理props或$emit的传值
- 具有缓存性,页面重新渲染值不变化,计算属性会立即返回之前的计算结果,而不必再次执行函数
watch特性
- 应用:监听props,$emit或本组件的值执行异步操作
- 无缓存性,页面重新渲染时值不变化也会执行
二、computed
定义
是一个计算属性,对数据进行过滤器处理
用法
1、get用法
data: {
firstName: 'Tom',
lastName: 'Jerry'
},
computed: {
fullName: function () {
return this.firstName + ' ' + this.lastName
}
}
注意: computed
中的属性如fullName
不可在data
里面定义,否则会报错
2、get和set用法
data: {
firstName: 'Foo',
lastName: 'Bar'
},
computed: {
fullName:{
get(){ // 回调函数 当需要读取当前属性值时执行
return this.firstName + ' ' + this.lastName
},
set(val){ // 监视当前属性值的变化,val就是fullName的最新属性值
const names = val.split(' ');
this.firstName = names[0];
this.lastName = names[1];
}
}
}
三、watch
定义
是一个监听属性,对数据进行监听处理
用法
1、监听简单数据类型
data(){
return{
'first': 1
}
},
watch:{
first(){
console.log(this.first)
}
}
2、监听复杂数据类型
监听复杂数据类型需用深度监听
data(){
return{
'first':{
second: 2
}
}
},
watch:{
'first.second'(oldVal,newVal){
console.log(oldVal, newVal);
}
}
3、监听对象单个属性
方法一: 可以直接对用对象.属性
的方法拿到属性
data(){
return{
'first':{
second: 2
}
}
},
watch:{
first.second: function(newVal, oldVal){
console.log(newVal, oldVal);
}
}
方法二: watch如果想要监听对象的单个属性的变化,必须用computed
作为中间件转化,因为computed
可以取到对应的属性值
data(){
return{
'first':{
second: 2
}
}
},
computed: {
showNum() {
return this.first.second;
}
},
watch: {
showNum(newVal, oldVal) {
console.log(`new:${newVal}, old:${oldVal}`);
}
}