computed

Computed, which looks like a method, is really a computed property, and it dynamically displays computed results based on data dependencies, and the computed results are cached (vue does this specially)

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

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

Computed is used in environments where recalculation takes time and does not involve repeated data computations, and the this context of getters and setters is automatically bound to Vue instances. If a data is dependent on other data, you can design it for computed

watch

The Vue function calls $watch() on instantiation to traverse each property of the watch object. The immediate property indicates whether the function is executed on the first rendering. Deep means that when listening for an object, it looks for changes in its properties and executes a function if one of the properties changes.

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; // The watch n function calls this asynchronously.$nextTick(() => {
        this.inUndoMode = false; }); //nextTick delay callback}}}).$mount("#app");
Copy the code