How to Fix 'Computed Property Was Assigned' Error in Vue
computed properties are read-only by default and cannot be assigned values directly. To fix the error, avoid assigning to a computed property and instead update the underlying reactive data or use a computed setter if you need two-way binding.Why This Happens
Vue's computed properties are designed to automatically calculate values based on reactive data. They are read-only by default, so trying to assign a value directly to a computed property causes an error. This happens because computed properties are like formulas, not variables you can set.
export default { data() { return { count: 0 }; }, computed: { doubleCount() { return this.count * 2; } }, methods: { updateDouble() { this.doubleCount = 10; // ❌ This causes the error } } };
The Fix
Instead of assigning a value directly to a computed property, update the reactive data it depends on. If you want to assign to a computed property, define a setter function inside the computed property to handle the assignment properly.
export default { data() { return { count: 0 }; }, computed: { doubleCount: { get() { return this.count * 2; }, set(value) { this.count = value / 2; } } }, methods: { updateDouble() { this.doubleCount = 10; // ✅ This updates count to 5 } } };
Prevention
Always treat computed properties as read-only unless you explicitly define a setter. Use reactive data or ref variables for values you want to change directly. Enable linting rules like vue/no-mutating-props to catch improper assignments early.
Follow these best practices:
- Use computed getters for derived state.
- Use setters only when two-way binding is needed.
- Update underlying data, not computed properties, in methods.
Related Errors
Other common Vue errors related to computed properties include:
- "Computed property has no getter": Happens if you define a computed property without a return value.
- "Avoid mutating a prop directly": Occurs when trying to assign a value to a prop instead of emitting events.
Fix these by ensuring computed properties return values and props are treated as read-only.