你很容易滥用 watch

版权声明:转载原创文章请注明:文章转载自:前端精髓 https://blog.csdn.net/wu_xianqiang/article/details/82114268

Vue 提供了一种更通用的方式来观察和响应 Vue 实例上的数据变动:侦听属性。当你有一些数据需要随着其它数据变动而变动时,你很容易滥用 watch,然而,通常更好的做法是使用计算属性而不是命令式的 watch 回调。细想一下这个例子:

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
    }
  }
})
var vm = new Vue({
  el: '#demo',
  data: {
    firstName: 'Foo',
    lastName: 'Bar'
  },
  computed: {
    fullName: function () {
      return this.firstName + ' ' + this.lastName
    }
  }
})

猜你喜欢

转载自blog.csdn.net/wu_xianqiang/article/details/82114268