简述 computed 和 watch 的区别

102 阅读1分钟

computed

computed从字面意思上来讲的意思就是 计算, 在Vuecomputed 就是当依赖的某个 state 变化时得到一个新的state

new Vue({
  data() {
    return {
      age: 10
    }
  }
  template: `
  <div>
  <button @click="click"></button>
  {{ageMsg}}
  </div> 

  `,
  methods: {
    click() {
      this.age = 18
    }
  },
  computed: {
    ageMsg(){
      return this.age > 17 ? '成年' : '未成年'
    }
  }
})

watch

watch 字面意思就看, 在Vue 中就是观察某个state 变化去执行一段逻辑来达到某种效果

new Vue({
  el: '#watch-example',
  data: {
    question: '',
    answer: 'I cannot give you an answer until you ask a question!'
  },
  watch: {
    // 如果 `question` 发生改变,这个函数就会运行
    question: function (newQuestion, oldQuestion) {
      this.answer = 'Waiting for you to stop typing...'
      this.debouncedGetAnswer()
    }
  },
  created: function () {
  },
  methods: {}
})

总结一下 computed 适合用来在一个state 变化之后得到一个新的state用于重新渲染,watch 适合在一个state 变化之后发起异步操作或者执行新的逻辑, 最终目的是执行一个函数来得到某个结果