启东市住房城乡建设局网站百度推广助手app下载
在 Vue 2 中,计算属性 (computed properties
) 是基于其他数据属性计算得出的属性。计算属性本身是只读的,不能直接修改其值。如果你需要修改计算属性的值,通常需要修改其依赖的数据属性。
假设你有一个计算属性 fullName
,它依赖于 firstName
和 lastName
:
new Vue({el: '#app',data: {firstName: 'John',lastName: 'Doe'},computed: {fullName: function() {return this.firstName + ' ' + this.lastName;}}
});
如果你想修改 fullName
,你需要修改 firstName
或 lastName
:
// 修改 firstName 和 lastName
this.firstName = 'Jane';
this.lastName = 'Smith';
如果你希望直接修改计算属性,可以使用计算属性的 getter
和 setter
。例如:
new Vue({el: '#app',data: {firstName: 'John',lastName: 'Doe'},computed: {fullName: {get: function() {return this.firstName + ' ' + this.lastName;},set: function(newValue) {var names = newValue.split(' ');this.firstName = names[0];this.lastName = names[names.length - 1];}}}
});
this.fullName = 'Jane Smith';
这样,firstName
会变成 Jane
,lastName
会变成 Smith
。
注意: 在计算属性set当中不可以直接修改。例如this.fullName = newValue。
computed: {fullName: {get: function() {return this.firstName + ' ' + this.lastName;},set: function(newValue) {this.fullName = newValue;}}}
注意:不能进行异步计算