Vue2的计算属性
在Vue2文档上存在这么一个例子:通过计算属性来获取全名
var vm = new Vue({
el: '#demo',
data: {
firstName: 'Foo',
lastName: 'Bar'
},
computed: {
fullName: function () {
return this.firstName + ' ' + this.lastName
}
}
})
同时,如果我们更改了计算属性时,响应式数据也需要同步更改,所以文档上还给出了另外一个完善的例子:计算属性默认只有 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]
}
}
}
在Vue3中按照Vue2的模式使用计算属性
之前在