Protect state with readonly
State that anyone can change is state you cannot reason about. When you hand a
piece of state to another part of your app, you often want it readable but not
writable. readonly returns a proxy that blocks every write:
<script setup>
import { reactive, readonly } from 'vue';
const state = reactive({ count: 0 });
const view = readonly(state);
</script>
<template>
<button @click="view.count++">Count: {{ view.count }}</button>
</template>
The button reads view.count, but assigning to it does nothing — Vue warns in
development and ignores the write, so the label stays Count: 0. The underlying
state is still mutable: change state.count and both state and view
update.
Use readonly to expose state without exposing the ability to change it. The
read-only view stays connected to the source, so it always shows the current
value, but only the owner of the original object can change it.
The Test for this Lesson mounts your component, clicks the button once, and
checks the label. Your component is exported from App.vue.
Challenge
The button changes the count, but it should not. Wrap the state in readonly so
the write is blocked: export an App component from App.vue that renders a
button labelled Count: 0 whose click cannot change the count.
The Test mounts your component, clicks the button once, and expects the label to
still read Count: 0. The starter exposes the mutable state, so the count
becomes 1 and the Test fails.