《学习笔记Vue—— computed与watch的区别》

150 阅读1分钟

computed与watch的区别

computed

  1. 用来计算属性,它会根据数据的改变显示新的计算结果,计算结果会被缓存。
  2. 如果以来的属性没有变化,就不会重新计算
  3. getter/setter默认不会做缓存,Vue做了特殊处理
  4. 不用加括号,可以当成属性使用

代码案例:

new Vue({
  data: {
   user: {
    email: "123123123@qq.com",
    nickname: "一",
    phone: "123123123"
    }
  },
  computed: {
    displayName: {
      get() {
        const user = this.user;
        return user.nickname || user.email ||user.phone;
      },
     set(value) {
       this.user.nickname = value;
       }
     }
  },
// 不如用 computed 来计算 displayName
template: `
 <div>
    {{displayName}}
  <div>
  {{displayName}}
  <button @click="add">set</button>
  </div>
</div>
`,
methods: {
  add() {
    this.displayName = "零";
   }
 }
 }).$mount("#app");

应用场景

适用于重新计算比较费时不用重复数据计算的环境。所有 getter 和 setter 的 this 上下文自动地绑定为 Vue 实例。如果一个数据依赖于其他数据,那么把这个数据设计为computed

watch

watcher 更像是一个 data 的数据监听回调,当依赖的 data 的数据变化,执行回调,在方法中会传入 newVal 和 oldVal。可以提供输入值无效,提供中间值 特场景。Vue 实例将会在实例化时调用 $watch(),遍历 watch 对象的每一个属性。如果你需要在某个数据变化时做一些事情,使用watch。

代码案例:

new Vue({
 data: {
  n: 0,
  history: [],
  inUndoMode: false
 },
watch: {
  n: function(newValue, oldValue) {
     if (!this.inUndoMode) {
     this.history.push({ from: oldValue, to: newValue
     });
    }
   }
  },
// 不如用 computed 来计算 displayName
template: `
 <div>
  {{n}}
  <button @click="add1">+1</button>
  <button @click="add2">+2</button>
  <button @click="minus1">-1</button>
  <button @click="minus2">-2</button>
  <button @click="undo">撤销</button>
  {{history}}
 </div>
`,
methods: {
 add1() {
  this.n += 1;
 },
 add2() {
  this.n += 2;
 },
 minus1() {
  this.n -= 1;
 },
 minus2() {
  this.n -= 2;
 },
 undo() {
   const last = this.history.pop();
   this.inUndoMode = true;
   const old = last.from;
   this.n = old; // watch n 的函数会异步调用  
   this.$nextTick(() => {
   this.inUndoMode = false;
  });
 }
}
}).$mount("#app");
  • deep:监听对象内部值的变化
  • immediate:在选项参数中指定 immediate: true 将立即以表达式的当前值触发回调

总结

1.如果一个数据依赖于其他数据,那么把这个数据设计为computed的  

2.如果你需要在某个数据变化时做一些事情,使用watch来观察这个数据变化

3.watch 支持异步代码而 computed 不行