Performance: Provide and inject for deep passing
This affects how data is passed deeply through component trees without prop drilling, impacting rendering and reactivity performance.
const Parent = { provide() { return { value: this.value } }, data() { return { value: 0 } }, template: `<Child1 />` } const Child1 = { inject: ['value'], template: `<Child2 />` } const Child2 = { inject: ['value'], template: `<Child3 />` } const Child3 = { inject: ['value'], template: `<div>{{ value }}</div>` }
const Parent = { template: `<Child1 :value=\"value\" />`, data() { return { value: 0 } } } const Child1 = { props: ['value'], template: `<Child2 :value=\"value\" />` } const Child2 = { props: ['value'], template: `<Child3 :value=\"value\" />` } const Child3 = { props: ['value'], template: `<div>{{ value }}</div>` }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Prop drilling through many components | Many prop updates | Multiple reflows | Higher paint cost | [X] Bad |
| Provide/inject for deep passing | Single reactive source | Minimal reflows | Lower paint cost | [OK] Good |
provide and inject in Vue?provide in a Vue 3 setup function?import { provide, inject } from 'vue';
export default {
setup() {
provide('color', 'blue');
}
}
// In child component
export default {
setup() {
const color = inject('color');
console.log(color);
}
}export default {
setup() {
provide = { theme: 'dark' };
}
}
export default {
setup() {
const theme = inject('theme');
return { theme };
}
}reactive() and inject it directly. Vue automatically ensures the injected value is deeply reactive in descendants.reactive() in each child. uses a plain object (no reactivity) and re-wrapping creates separate instances. Provide a ref with the reactive object and inject the ref, then use .value in children. unnecessarily wraps a reactive object in a ref, adding extra complexity with .value. Provide a reactive object but inject a copy using { ...injected } to avoid mutation. copies the object, breaking the reactivity connection.reactive() and inject it directly. -> Option DPass the test and this pattern moves unknown