Consider this Vue 3 setup using provide and inject. What will the child component display?
/* Parent.vue */ <script setup> import { provide } from 'vue' const message = 'Hello from parent' provide('msg', message) </script> <template> <Child /> </template> /* Child.vue */ <script setup> import { inject } from 'vue' const msg = inject('msg', 'Default message') </script> <template> <p>{{ msg }}</p> </template>
Remember that provide passes data down the component tree and inject receives it.
The parent uses provide to share the string 'Hello from parent' with the key 'msg'. The child uses inject with the same key, so it receives that string and displays it.
Choose the correct syntax to inject a provided value named config in a Vue 3 component using inject.
Inject accepts a key string and optionally a default value.
Option A correctly calls inject with the key 'config' and a default value. Option A misses the default value but is valid syntax; however, the question asks for the correct way including fallback. Option A wrongly uses provide. Option A passes a variable instead of a string key.
Given this parent and child component, why is the injected value in the child not reactive?
/* Parent.vue */ <script setup> import { provide, ref } from 'vue' const count = ref(5) provide('count', count.value) </script> <template> <Child /> </template> /* Child.vue */ <script setup> import { inject } from 'vue' const count = inject('count', 0) </script> <template> <p>{{ count }}</p> </template>
Think about reactivity and how ref values are passed.
The parent provides count.value, which is a primitive number, not reactive. The child injects that static number. To keep reactivity, the parent should provide the ref itself, not its value.
Why do developers use dependency injection patterns like provide and inject in Vue 3?
Think about how data flows between components.
Dependency injection allows passing data or services from ancestor to descendant components without passing props through every intermediate component, avoiding prop drilling.
Analyze this Vue 3 code. What will the child component display after the button is clicked once?
/* Parent.vue */ <script setup> import { ref, provide } from 'vue' const count = ref(0) provide('count', count) function increment() { count.value++ } </script> <template> <button @click="increment">Increment</button> <Child /> </template> /* Child.vue */ <script setup> import { inject } from 'vue' const count = inject('count') </script> <template> <p>Count is: {{ count.value }}</p> </template>
Remember that ref is reactive and shared via provide/inject.
The parent provides a reactive ref count starting at 0. Clicking the button increments count.value to 1. The child injects the same reactive ref and displays the updated value.