0
0
VueHow-ToBeginner · 3 min read

How to Use readonly in Vue: Simple Guide with Examples

In Vue 3, use the readonly function from vue to create a reactive object that cannot be changed. This helps protect data from accidental modification while still allowing reactivity in your components.
📐

Syntax

The readonly function takes a reactive object and returns a new reactive proxy that prevents any changes to the original data. It is imported from the vue package.

  • readonly(object): Wraps the object to make it immutable.
javascript
import { reactive, readonly } from 'vue';

const state = reactive({ count: 0 });
const readOnlyState = readonly(state);
💻

Example

This example shows a Vue component where a reactive state is wrapped with readonly. The component can read the state but cannot modify it directly through the readonly proxy.

vue
<template>
  <div>
    <p>Count: {{ readOnlyState.count }}</p>
    <button @click="increment">Increment</button>
    <button @click="tryModify">Try Modify Readonly</button>
  </div>
</template>

<script setup>
import { reactive, readonly } from 'vue';

const state = reactive({ count: 0 });
const readOnlyState = readonly(state);

function increment() {
  state.count++;
}

function tryModify() {
  // This will fail silently or warn in dev mode
  readOnlyState.count++;
}
</script>
Output
Count: 0 [Increment button] [Try Modify Readonly button]
⚠️

Common Pitfalls

Trying to modify a readonly object directly will not work and may cause warnings in development mode. Remember that readonly only prevents changes through the proxy, but the original reactive object can still be changed.

Also, readonly does not deep freeze plain objects outside Vue's reactivity system.

javascript
import { reactive, readonly } from 'vue';

const state = reactive({ value: 10 });
const readOnlyState = readonly(state);

// Wrong: This does nothing and may warn
readOnlyState.value = 20;

// Right: Change original reactive object
state.value = 20;
📊

Quick Reference

  • Import: import { readonly } from 'vue'
  • Use: Wrap reactive objects to prevent direct mutation
  • Behavior: Readonly proxies allow reading but block writes
  • Note: Original reactive object can still be changed

Key Takeaways

Use Vue's readonly() to create immutable reactive proxies that prevent direct changes.
Readonly objects allow reading reactive data but block any modifications through them.
Always modify the original reactive object, not the readonly proxy.
Readonly helps protect state in components from accidental mutation.
Readonly does not deep freeze plain objects outside Vue's reactivity system.