Computed和watch

95 阅读1分钟

Computed - 计算属性

被计算出来的属性就是计算属性

例:

new Vue({
  data: {
    user: {
      email: "123456789@qq.com",
      nickname: "小明",
      phone: "18299999999",
    },
  },

  computed: {
    displayName: {
      get() {
        const user = this.user;
        return user.nickname || user.email || user.phone;
      },
      set(value) {
        this.user.nickname = value;
      },
    },
  },
  template: `
    <div>
    {{displayName}}
    <div>
    {{displayName}}
    <button @click="add">set</button>
    </div>
    </div>
    `,
  methods: {
    add() {
      this.displayName = "小花";
    },
  },
}).$mount("#app");

缓存:
如果依赖的属性没有变化,就不会重新计算。
getter和setter默认不做缓存,Vue做了特殊的处理。

Watch - 侦听

当属将要发生变化时,执行一个函数

new Vue({
  data: {
    n: 0,
    history: [],
    inUndoMode: false,
  },
  watch: {
    n(nweValue, oldValue) {
      if (!this.inUndoMode) {
        this.history.push({ from: oldValue, to: nweValue });
      }
    },
  },
  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();
      const old = last.from;
      this.inUndoMode = true;
      this.n = old;
      this.$nextTick(() => {
        this.inUndoMode = true;
      }, 0);
    },
  },
}).$mount("#app");

何为变化?

  • 假设一个对象obj原本为{n:0},将n+1,请问n是否改变? 答:n变了
  • 假设一个对象obj原本为{a:'a'},将obj.a += 'hi',请问obj与obj.a的变化?答:obj没变,obj.a变了
  • 假设一个对象obj原本为{a:'a'},将"obj = {a:'a'},请问obj与obj.a的变化?答:obj变了,obj.a没变
  • 简单类型看值,复杂类型(对象)看地址

deep:ture是干什么的?

如果object.a变了,请问object算不算发生变化?
如果答案为改变了,那么就用deep:ture
如果答案是没有改变,那么就用deep:falese
deep的意思是,是否监听object更深一层

watch后面千万不能接箭头函数,因为箭头函数没有this,这里的this是全局对象

computed和watch的区别

computed是用来计算属性的,watch是用来侦听的。computed依赖数据的变化重新计算,不需要函数调用而是将其类似于属性直接调用。watch侦听某个属性,当属性发生变化了,则执行相应的函数,immediate用来显示第一次变化,deep属性用来侦听更深一层的属性变化。