0 day streak
javascript / intermediate
Snippet

Immutable State with readonly()

The readonly() function takes a reactive or plain object and returns a read-only proxy to the original. This is useful for exposing state that should only be mutated by specific internal logic, preventing accidental changes from consumer components.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
import { reactive, readonly } from 'vue';
const state = reactive({ count: 0 });
const lockedState = readonly(state);
// This will trigger a warning and fail in development
// lockedState.count++;
const increment = () => state.count++;
vue
Breakdown
1
const lockedState = readonly(state);
Creates a deep read-only proxy of the reactive state object.
2
lockedState.count++;
Any attempt to mutate the locked state will result in a console warning.