Vue 里 computed 和 watch 的区别

218 阅读1分钟

什么是computed

computed就是计算属性 , computed 是用来计算出一个值,这个值在调用的时候会根据依赖的数据显示新的计算结果并自动缓存。 如果依赖不变,computed中的值就不会重新计算。 注意 :不需要加(),

以下是代码示例

// 引用完整版 Vue,方便讲解
import Vue from "vue/dist/vue.js";

Vue.config.productionTip = false;

new Vue({
  data: {
    user: {
      email: "fangyinghang@qq.com",
      nickname: "方方",
      phone: "13812312312"
    }
  },
  computed: {
    displayName: {
      get() {
        const user = this.user;
        return user.nickname || user.email || user.phone;
      },
      set(value) {
        console.log(value);
        this.user.nickname = value;
      }
    }
  },
  // DRY don't repeat yourself
  // 不如用 computed 来计算 displayName
  template: `
    <div>
      {{displayName}}
      <div>
      {{displayName}}
      <button @click="add">set</button>
      </div>
    </div>
  `,
  methods: {
    add() {
      console.log("add");
      this.displayName = "圆圆";
    }
  }
}).$mount("#app");

计算属性和方法的区别

  • 计算属性是基于他们的响应式依赖进行缓存的,只在相关响应式依赖发生改变时,才会重新求值(也就是说,计算属性会把数据进行缓存)
  • 而方法不会把数据进行缓存, 所以用计算属性效率会更高点

什么是watch

watch监听的数据可以是一个 字符串、函数、数组、对象 一个对象,键是需要观察的表达式(data内的数据),值是对应回调函数。值也可以是方法名,或者包含选项的对象。 当数据发生改变时,会执行一个回调,它有俩个参数, newVal 和 oldVal

wtach有俩个属性:

  • immediate 是否在第一次渲染时执行这个函数,会在监听开始之后就立即本调用。
  • deep 是否要看这个对象里面的属性变化。

以下是代码示例:

// 引用完整版 Vue,方便讲解
import Vue from "vue/dist/vue.js";

Vue.config.productionTip = false;

new Vue({
  data: {
    n: 0,
    history: [],
    inUndoMode: false
  },
  watch: {
    n: function(newValue, oldValue) {
      console.log(this.inUndoMode);
      if (!this.inUndoMode) {
        this.history.push({ from: oldValue, to: newValue });
      }
    }
  },
  // 不如用 computed 来计算 displayName
  template: `
    <div>
      {{n}}
      <hr />
      <button @click="add1">+1</button>
      <button @click="add2">+2</button>
      <button @click="minus1">-1</button>
      <button @click="minus2">-2</button>
      <hr/>
      <button @click="undo">撤销</button>
      <hr/>

      {{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;
      console.log("ha" + this.inUndoMode);
      const old = last.from;
      this.n = old; // watch n 的函数会异步调用
      this.$nextTick(() => {
        this.inUndoMode = false;
      });
    }
  }
}).$mount("#app");

总结

  1. 如果一个数据需要经过复杂计算就用 computed
  2. 如果一个数据需要在发生变化时做一些操作就用 watch