Vue 3 provide/inject cross-component communication
In Vue 3, provide and inject are options used for parent components to pass data down to child components. By using the provide option, a parent component can supply data, while a child component can use the inject option to receive this data. This method of data passing enables communication between components across multiple levels without explicitly passing data through props.
Below is an example demonstrating how to use the provide and inject options in Vue 3:
// Parent Component
export default {
name: 'ParentComponent',
data() {
return {
message: 'Hello from parent'
};
},
provide() {
return {
message: this.message
};
},
// ...
}
In the code above, the ParentComponent uses the provide option to expose a data property named message. The provide option returns an object where the keys represent the names of the data being provided and the values are the actual data.
// Child Component
export default {
name: 'ChildComponent',
inject: ['message'],
created() {
console.log(this.message); // Output: Hello from parent
},
// ...
}
In the ChildComponent, we use the inject option to declare that we wish for data named message to be injected. The inject option accepts either an array or an object specifying the names of the data to be injected; in this example, we specify message. Once a corresponding piece of data changes within the parent component, the child component will automatically update to reflect the latest value.
It is important to note that the use of provide and inject options should be handled with caution. They create a coupling relationship between ancestor and descendant components, which can lead to unclear dependencies between them. Therefore, when sharing data across multiple levels of components, it is recommended to first consider if there are better approaches for component communication, such as using props or state management solutions like Vuex.