Computed-属性-vs-Watched-属性

来源:互联网 发布:淘宝网老是要重新登录 编辑:程序博客网 时间:2024/06/07 05:23
Vue 确实提供了一种更通用的方式来观察和响应 Vue 实例上的数据变动:watch 属性。当你有一些数据需要随着其它数据变动而变动时,你很容易滥用 watch——特别是如果你之前使用过 AngularJS。然而,通常更好的想法是使用 computed 属性而不是命令式的 watch 回调。细想一下这个例子:
<div id="demo">{{ fullName }}</div>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    }  }})

上面代码是命令式的和重复的。将它与 computed 属性的版本进行比较:

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


原创粉丝点击