Vue Computed Properties

Vue Computed Properties
They are cached, meaning they run only when their dependencies change.
What are Computed Properties?
Computed properties are functions that behave like data properties.
- Automatically update when dependent data changes
- Cached for better performance
- Ideal for calculations, filtering, formatting
Basic Syntax
Example-1: Simple Computed Property
fullNameupdates automatically whenfirstNameorlastNamechanges.
Example-2: Computed vs Method
- Runs only when
priceorquantitychanges - Method would run on every re-render
Example-3: Filtering with Computed
- Best practice instead of
v-ifinsidev-for
Example-4: Computed with Getter & Setter
- Enables two-way computed logic
Computed vs Methods (Important)
| Feature | Computed | Methods |
|---|---|---|
| Cached | Yes | No |
| Reactive | Yes | Yes |
| Best for | Derived data | Actions / events |
| Performance | High | Lower |
- Use computed for calculations
- Use methods for event handling
Computed vs Watchers
| Feature | Computed | Watch |
|---|---|---|
| Purpose | Derive value | React to change |
| Return value | Yes | No |
| Side effects | No | Yes |
- Computed → data transformation
- Watch → API calls, logging
Common Use Cases
Full name generation
Price calculations
Filtering lists
Sorting data
Conditional classes
Validation logic
Common Mistakes
- Doing API calls in computed
- Mutating data inside computed
- Using methods instead of computed
Best Practices
- Keep computed pure (no side effects)
- Use meaningful names
- Prefer computed over methods for derived data
- Use setter only when needed
Summary Table
| Use Case | Use |
|---|---|
| Calculated value | Computed |
| Filtering lists | Computed |
| Formatting output | Computed |
| Click handling | Methods |
| Side effects | Watchers |
Conclusion
Computed properties are one of the most powerful features of Vue.
They help you write clean, fast, and maintainable code by separating logic from templates.
