Responding to Reactivity with Provide/Inject
Explain how to make the injected data reactive by using a ref or reactive from Vue's reactivity system, and how changes to the data are reflected across the components.
import { provide, ref } from 'vue';
export default {
setup() {
// Create a reactive reference
const reactiveData = ref('Initial Value');
// Provide the reactive data to descendants
provide('reactiveKey', reactiveData);
return {};
}
};
This is a setup function of a Vue component that uses `provide` to make reactive data available to its descendant components. A ref is used to ensure the provided data is reactive.
import { inject } from 'vue';
export default {
setup() {
// Inject the reactive data provided by an ancestor component
const reactiveData = inject('reactiveKey');
// Use a computed or watch to respond to changes in the reactive data
// reactiveData.value could be used directly in the template or computed properties
return {
reactiveData
};
}
};
This code snippet represents a setup function within a descendant component that injects the provided reactive data using the `inject` function. The injected data is made available in the component for use and is automatically reactive, meaning it will update whenever the source ref changes.