Intermediate LevelVue JS
How does readonly() create immutable proxies for safely sharing reactive state?
❓ Interview Prompt: Explain readonly() proxy wrapper, preventing external state mutation, and export patterns in composables.
When sharing reactive state from a composable or global store, allowing external components to mutate state directly leads to unpredictable bugs.
'readonly(reactiveObject)':
Creates a read-only Proxy wrapper around a reactive object or ref. Any attempt to mutate a 'readonly' property raises a console warning (or error in strict mode), enforcing one-way data flow!
Code Implementation Example
javascript
import { ref, readonly } from 'vue';
const state = ref({ count: 0 });
const increment = () => state.value.count++;
// Export state as READONLY; expose increment function for mutation!
export function useCounter() {
return {
state: readonly(state), // External consumers CANNOT write state.value.count = 99!
increment
};
}💡Protecting reactive state against external mutation using readonly().
🎯 Interview Key Takeaway
Wrap exported reactive state in readonly() to prevent external component mutations and enforce strict one-way data flow.
#readonly#Immutability#Reactivity#Intermediate
Back to all Vue JS Questions→