Computed属性
简单理解就是将一堆计算抽离成简单的一个属性,并且拥有缓存机制(值变化才会重新计算,否则立即返回)
官网举例:
<div id="example"><p>Original message: "{{ message }}"</p><p>Computed reversed message: "{{ reversedMessage }}"</p></div>var vm = new Vue({el: '#example',data: {message: 'Hello'},computed: {// a computed getter 定义一个computed属性,它的值会根据 message的变化而变化reversedMessage: function () {// `this` points to the vm instancereturn this.message.split('').reverse().join('')}}})
Computed VS Methods
Computed属性和普通methods的区别在于:computed properties are cached based on their dependencies。不是每次调用都会执行,而是根据其依赖的属性变化而变化
Computed VS Watched Property
Vue提供了另一种响应数据变化的属性叫 Watched Property,当你有一些数据需要基于其他数据的变化而变化时,虽然Watched属性能满足,但是考虑如下场景,Computed属性会变得更友好 简洁
var vm = new Vue({el: '#demo',data: {firstName: 'Foo',lastName: 'Bar',fullName: 'Foo Bar'},//watch属性会跟着firstName,lastName分开一起变,但是都要执行一次操作,如果同时变,操作会变为两次watch: {firstName: function (val) {this.fullName = val + ' ' + this.lastName},lastName: function (val) {this.fullName = this.firstName + ' ' + val}}// computed属性无论何时,只需计算一次即可computed: {fullName: function () {return this.firstName + ' ' + this.lastName}}})
Computed setter
默认Computed提供了getter方法,但是也可以通过如下方式来提供setter方法
computed: {fullName: {// getterget: function () {return this.firstName + ' ' + this.lastName},// setterset: function (newValue) {var names = newValue.split(' ')this.firstName = names[0]this.lastName = names[names.length - 1]}}}
