watch和computed的区别

139 阅读1分钟

什么是watch和computed?

  • watch是用来监听一个值的变化。
  • computed是计算属性,用来计算的,返回计算后的结果,对于复杂逻辑,都应该使用计算属性,开始是设计在模板内的表达式内的,由于不利于维护,所以后来写到了计算属性中。

watch的使用

  • 不带immediate和deep
  <script>
var vm = new Vue({
  el: '#demo',
  data: {
    firstName: 'Foo',
    lastName: 'Bar',
    fullName: 'Foo Bar'
  },
  watch: {
    firstName: function (val) {
      this.fullName = val + ' ' + this.lastName
    },
    lastName: function (val) {
      this.fullName = this.firstName + ' ' + val
    }
  }
})
    </script>  


这样fullName的值就会发生改变,用watch进行监听。

  • 带immediate和deep
  watch: {
       WatchCaseLibrary: {
            handler(newName, oldName) {
                this.allTableData = newName
            },
            immediate: true,
            deep:true
       }
    },

加上immediate代表立即执行,deep用于监听对象值的改变。

computed的使用

var vm = new Vue({
  el: '#demo',
  data: {
    firstName: 'Foo',
    lastName: 'Bar'
  },
  computed: {
    fullName: function () {
      return this.firstName + ' ' + this.lastName
    }
  }
})

这样就可以得到fullName是'FooBar'。

  • 计算属性默认只有getter,需要的时候也可以提供setter
computed: {
  fullName: {
    // getter
    get: function () {
      return this.firstName + ' ' + this.lastName
    },
    // setter
    set: function (newValue) {
      var names = newValue.split(' ')
      this.firstName = names[0]
      this.lastName = names[names.length - 1]
    }
  }
}

有了setter,firstName和lastName的值就会发生改变。