Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

watch和computed的区别 #84

Open
TieMuZhen opened this issue Feb 27, 2022 · 0 comments
Open

watch和computed的区别 #84

TieMuZhen opened this issue Feb 27, 2022 · 0 comments
Labels

Comments

@TieMuZhen
Copy link
Owner

TieMuZhen commented Feb 27, 2022

一、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}`);
  }
}

参考文献

@TieMuZhen TieMuZhen added the Vue label Feb 27, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant