In Vue.js, computed is used to calculate response data and automatically updated; methods is used to execute executable code and needs to be called manually. computed depends on other response data and is automatically recalculated when dependencies change; methods are not affected by response data and must be called manually. computed uses the getter function and can only return calculated values; methods can contain any code. Prefer computed to improve performance and code clarity, and avoid performing complex operations in computed.
The difference between computed and methods in Vue.js
In Vue.js, computed and methods are used Different ways to define response data. The main difference between them is:
1. Computed property (computed)
2. Methods
Detailed comparison
Features | computed | methods |
---|---|---|
Purpose | Calculate response data | Execute executable code |
Dependencies | Depends on other response data | None |
Trigger update | Automatically update when dependencies change | Required Manually call |
Data type | The value returned by the getter function | can contain any code |
Use Method | Use in template orthis.$computed.propertyName Access |
Use in templatethis.$methods.methodName() Access |
Performance | Recalculated when dependencies change, performance depends on the calculation logic | Executed when called, performance depends on the complexity of the method |
Usage example
computed:
<code class="javascript">export default { computed: { fullName() { return this.firstName + ' ' + this.lastName; } } };</code>
methods:
<code class="javascript">export default { methods: { greet() { console.log('Hello, ' + this.name); } } };</code>
Choose which method to use
Notes
The above is the detailed content of The difference between computed and methods in vue. For more information, please follow other related articles on the PHP Chinese website!