Performance: Readonly for immutable reactive data
This affects how Vue tracks and updates reactive data, impacting rendering speed and memory usage.
import { readonly } from 'vue'; const data = readonly({ name: 'Alice', age: 30 }); // data is immutable and not tracked for changes
import { reactive } from 'vue'; const data = reactive({ name: 'Alice', age: 30 }); // data is never changed but still reactive
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Reactive on immutable data | Tracks dependencies unnecessarily | Triggers re-renders on no changes | Extra paint cycles | [X] Bad |
| Readonly on immutable data | No dependency tracking | No unnecessary re-renders | Minimal paint cycles | [OK] Good |
readonly function do in Vue's reactivity system?readonlyreadonly function wraps a reactive object to prevent direct modifications, making it immutable.readonly keeps the object reactive but disallows changes.readonly to make it immutable.readonly. const data = reactive(readonly({ count: 0 })) tries to make a readonly object reactive, which is invalid. const data = readonly({ count: 0 }) skips reactive, so no reactivity. const data = reactive({ count: 0 }).readonly() uses a non-existent method.const state = reactive({ count: 1 });
const readOnlyState = readonly(state);
readOnlyState.count = 5;
console.log(readOnlyState.count);
state.count = 10;
console.log(readOnlyState.count);readOnlyState.count causes a warning in development mode, but the change is ignored and value remains 1.console.log(readOnlyState.count) outputs 1. Changing state.count to 10 updates the source, so second log is 10.import { reactive, readonly } from 'vue';
const data = readonly({ count: 0 });
data.count = 1;
console.log(data.count);data.count = 1.state shared across components. You want to expose it as readonly to prevent accidental changes but still reflect updates. Which approach correctly achieves this and why?
const state = reactive({ user: { name: 'Alice' }, count: 0 });
// Options:
// A) const safeState = readonly(state);
// B) const safeState = reactive(state);
// C) const safeState = readonly({ ...state });
// D) const safeState = reactive(readonly(state));Pass the test and this pattern moves unknown