Home >Web Front-end >Vue.js >How to solve Vue error: cannot use computed attribute
How to solve Vue error: Unable to use computed attribute
When using the Vue framework to develop projects, we often use the computed attribute to handle some calculations that need to be calculated based on the data attribute. out value. However, sometimes we may encounter Vue reporting an error, indicating that the computed attribute cannot be used. This problem may occur in the following situations:
In order to solve this problem, we can fix it in the following ways:
The sample code is as follows:
data() { return { age: 20, height: 180 } }, computed: { fullName: function() { return this.firstName + ' ' + this.lastName; }, isAdult: function() { return this.age >= 18; }, hasTallHeight: function() { return this.height > 175; } }
In the above code, we correctly defined three computed attributes: fullName, isAdult and hasTallHeight.
The sample code is as follows:
data() { return { firstName: 'John', lastName: 'Doe', age: 20, height: 180 } }, computed: { fullName: function() { return this.firstName + ' ' + this.lastName; }, isAdult: function() { return this.age >= 18; }, hasTallHeight: function() { return this.height > 175; } }
In the above code, the data attributes we rely on in the computed attribute have been correctly defined.
The sample code is as follows:
data() { return { age: 20, height: 180, fullName: '' } }, watch: { age: function(newVal, oldVal) { this.isAdult = newVal >= 18; }, height: function(newVal, oldVal) { this.hasTallHeight = newVal > 175; }, fullName: function(newVal, oldVal) { // 空函数,用于展示示例 } }, created() { this.fullName = this.firstName + ' ' + this.lastName; }
In the above code, we use the watch attribute to monitor changes in the age and height attributes, and calculate the values of the isAdult and hasTallHeight attributes responsively. To handle the calculation of the fullName attribute, we assign it in the created hook.
Summary
When we encounter an error that the computed attribute cannot be used in Vue development, we can check the definition and use of the computed attribute, and whether the data attribute on which the computed attribute depends is correct. definition to solve the problem. If that still doesn't work, we can try using the watch attribute as an alternative. Through the above method, we can solve the problem of Vue error: the computed attribute cannot be used, making our project more stable and reliable.
The above is the detailed content of How to solve Vue error: cannot use computed attribute. For more information, please follow other related articles on the PHP Chinese website!