Performance: Dependency injection patterns
This affects the initial load time and runtime responsiveness by controlling how dependencies are created and shared in Vue components.
import { provide, inject, reactive } from 'vue'; // In a parent or root component export default { setup() { const service = reactive({ count: 0 }); provide('service', service); return {}; } } // In child components export default { setup() { const service = inject('service'); return { service }; } }
import { reactive } from 'vue'; export default { setup() { const service = reactive({ count: 0 }); // Each component creates its own service instance return { service }; } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Creating new service instance per component | None | 0 | Low but repeated JS execution | [X] Bad |
| Using provide/inject to share service instance | None | 0 | Low JS execution once | [OK] Good |
provide and inject in Vue?import { provide, inject } from 'vue';
const Parent = {
setup() {
provide('message', 'Hello from parent')
}
}
const Child = {
setup() {
const msg = inject('message')
console.log(msg)
}
}import { provide, inject } from 'vue';
const Parent = {
setup() {
provide('data', 123)
}
}
const Child = {
setup() {
const data = inject('data')
console.log(data)
}
}provide('state', reactiveObj) and inject it normally in the grandchild correctly provides a reactive object and injects it normally, preserving reactivity. Provide a plain object and inject it with a default value in the grandchild uses a plain object, losing reactivity. Provide a reactive object but inject it inside onMounted hook in the grandchild delays injection unnecessarily. Provide a reactive object but convert it to a ref before injecting converts reactive to ref, which is unnecessary and may cause confusion.Pass the test and this pattern moves unknown