Using Provide/Inject and Ref for Cross-Component Communication in Vue
The article discusses common Vue component communication patterns such as props‑emit, event buses, and ref usage, then introduces a colleague's provide‑inject plus ref approach that simplifies cross‑component interactions while highlighting its trade‑offs regarding Vue's one‑way data flow.
Preface: In development you often encounter a scenario where a page has multiple regions, with a header component and a middle component as siblings, and a button in the header needs to modify the content of the middle component.
Typical solutions involve using props with emit, an event bus such as mitt, or accessing child components via ref from the parent.
props + emit
Parent component
Header component
Content component
This is the most common pattern: lift the title variable to the parent, let the Header emit an event, and let the parent update the title which flows down to Content via props.
emit + ref
Header emits an event; the parent obtains the Content component instance via ref and directly modifies the title.
mitt
Uses mitt’s emit and on for publish‑subscribe style data updates.
Colleague’s solution
The alternative approach uses provide + inject together with ref instances.
Parent component
Header component
Content component
Key ideas: (1) provide in the parent to expose all child component instances; (2) inject those instances into any component that needs them; (3) use the injected references to directly modify another component’s state or call its methods; (4) the target component must expose the needed properties or methods via defineExpose so they are accessible.
Summary
This provide/inject + ref method can reduce boilerplate in complex component trees, but it breaks Vue’s one‑way data flow, making the data flow less clear. Use it with caution.
Examples of scenarios where this approach helps are described, such as triggering a table refresh from a header button and simplifying communication among many sibling components.
Rare Earth Juejin Tech Community
Juejin, a tech community that helps developers grow.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.