readonly. What will be the console output after clicking the button?import { ref, readonly } from 'vue'; const state = ref({ count: 0 }); const readonlyState = readonly(state.value); function increment() { try { readonlyState.count++; } catch (e) { console.log('Error:', e.message); } } // Simulate button click increment(); console.log(readonlyState.count);
The readonly wrapper in Vue 3 creates an immutable reactive proxy. Trying to change its properties throws an error in strict mode. The count remains unchanged at 0.
import { reactive, readonly } from 'vue'; const state = reactive({ name: 'Alice' }); const readOnlyState = readonly(state); state.name = 'Bob'; console.log(readOnlyState.name);
The readonly proxy reflects the current state of the original reactive object. Changing state.name to 'Bob' updates readOnlyState.name as well.
Wrapping a reactive object with readonly creates a deeply readonly reactive proxy. Option D does this correctly.
state.user.name still be changed despite using readonly?import { readonly } from 'vue'; const state = { user: { name: 'John' } }; const readOnlyState = readonly(state); readOnlyState.user.name = 'Jane'; console.log(readOnlyState.user.name);
The readonly function creates a shallow readonly proxy. Nested objects inside a plain object remain mutable unless they are reactive.
readonly and JavaScript's Object.freeze when used for immutable data?Vue's readonly creates a reactive proxy that tracks dependencies and prevents mutations, enabling reactive updates. Object.freeze only prevents mutations but does not provide reactivity.
