Vue中computed和watch的区别

440 阅读1分钟

computed

computed看起来像是一个方法,实际上是计算属性,他会根据数据的依赖动态显示计算结果,计算结果会被缓存(vue做了特殊处理)

<template>
    <div class="people">
        {{fullName}}
    </div>
</template>

<script>
export default{
    data(){
        return {
            firstName:"杰",
            lastName:"森"
        }
    },
    props:{
        msg:String
    },
    computed:{
        fullName(){
            return this.firstName+''+this.lastName
        }
    }
}
</script>

computed用于重新计算比较费时不用重复数据计算的环境,getter和setter的this上下文自动绑定为Vue实例。如果一个数据依赖于其他数据,就可以将其设计为computed

watch

watch是数据监听,当data的数据发生变化,则执行回调函数,Vue函数在实例化时调用$watch()遍历watch对象的每一个属性,immediate属性代表是否在第一次渲染的时候执行函数,deep表示监听一个对象时是否看对象里面属性的变化,如果某个属性变化了,就执行一个函数。

new Vue({
  data: {
    n: 0,
    history: [],
    inUndoMode: false
  },
  watch: {
    n: function(newValue, oldValue) {
      if (!this.inUndoMode) {
        this.history.push({ from: oldValue, to: newValue });
      }
    }
  },
  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;
      const old = last.from;
      this.n = old; // watch n 的函数会异步调用
      this.$nextTick(() => {
        this.inUndoMode = false;
      });//nextTick延迟回调
    }
  }
}).$mount("#app");