Vue3 provide Function
provide The function is a higher-order function provided by Vue 3, used to pass data from a parent component to a child component in the component tree. Unlike the traditional props Compared toprovide and inject approach, it provides a more flexible way to share data, especially when the component hierarchy is deep.
Use provide function, the parent component can expose some data or methods to the child component, while the child component can receive them via the inject function.
Basic Usage of the provide Function
The following is a simple example showing how to use the provide function to provide data in the parent component, and receive it in the child component via the inject function.
Parent component
Example
Child component
Example
{{ injectedMessage }}
In this example, the parent component passes a string provide via the messagefunction, and the child component receives and displays this message via the inject function.
Advanced Usage of the provide Function
provide The function can pass not only simple data, but also methods, objects, and even reactive data. This makes it very useful in complex application scenarios.
Passing Reactive Data
In Vue 3, we can use ref or reactive to create reactive data and pass it via the provide function to the child component.
Example
In the child component, we can obtain this reactive object via the inject function and operate on it.
Example
Count: {{ state.count }}
Increment
Notes on the provide Function
When using provide When using the function, note the following points:
1. Naming Conflicts
When using provide and inject , if multiple parent components provide data with the same name, the child component will receive the data from the nearest parent component. Therefore, to avoid naming conflicts, unique names are recommended.
2. Handling Reactive Data
When passing reactive data, the child component can modify it directly. If you want the child component to only read but not modify the data, you can use the readonly function to wrap the reactive data.
Example
import { provide, reactive, readonly } from 'vue';
export default {
setup() {
const state = reactive({
count: 0
});
provide('state', readonly(state));
}
};
Vue3 Options API