In Vue.js, both methods and computed properties are used to define dynamic behavior in your Vue components, but they serve different purposes and have different behaviors.
Methods in Vue.js
Computed Properties in Vue.js
- Computed properties are functions defined within the computed object of a Vue component.
- They are similar to methods in that they compute a value, but they are cached based on their dependencies.
- Computed properties are only re-evaluated when their dependencies change. This means if the dependent data hasn't changed, Vue will return the previously computed result, which can improve performance.
- Computed properties are great for performing data manipulation or filtering.
// Vue component with a computed property
Vue.component('my-component', {
data() {
return {
items: [1, 2, 3, 4, 5]
};
},
computed: {
itemCount() {
return this.items.length;
}
}
});
Summary
Methods are called when explicitly invoked or in response to events, and they are re-evaluated on each render. Computed properties, on the other hand, are cached based on their dependencies and are only re-evaluated when those dependencies change. Use methods for operations that need to be explicitly invoked or for handling events, and use computed properties for derived data that depends on reactive data.