Menu

Vue provide/inject: Why You Should Never Skip readonly()
📰

Vue provide/inject: Why You Should Never Skip readonly()

DEV Community: vue·Parsa J·16 days ago
#3xljCpCd
#devtovue#devto#dev#cart#provide
Reading 0:00
15s threshold

A teammate asks you why cart.total changed. You open the component that renders it — nothing there mutates it. You check its parent — nothing there either. Twenty minutes later you find it: a <PromoBanner> three levels down, nowhere near the cart, called cart.items.push(...) because it had a reference to the object and nobody stopped it. Vue didn't do anything wrong. provide / inject handed that component the exact same reactive object the cart store holds, and JavaScript let it write to what it was handed. The bug isn't in Vue's reactivity — it's in a contract nobody enforced.

What You'll Learn

By the end of this article you'll be able to:

Explain why an injected value is a live reference, not a snapshot or a message

Reproduce the "mutation from anywhere" bug on purpose, so you recognize it in a real codebase

Apply Vue's own fix — readonly() on the provided value, paired with an exposed mutator function — and know exactly what it does and doesn't stop

Type provide / inject with InjectionKey<T> so…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.