vue3 inject provide
In Vue 3, the provide and inject functions are used for sharing data and methods between components in a parent-child relationship, without the need for explicit props passing.
The provide function is used in the parent component to make data or methods available to its child components. It takes a key-value pair as an argument, where the key is a unique identifier and the value is the data or method to be shared. Here's an example:
// Parent component
import { provide } from 'vue';
export default {
setup() {
provide('sharedData', 'Hello from parent!');
}
}
The inject function is used in the child component to access the provided data or methods. It takes the same key as the argument and returns the shared value. Here's an example:
// Child component
import { inject } from 'vue';
export default {
setup() {
const sharedData = inject('sharedData');
console.log(sharedData); // Output: Hello from parent!
}
}
Note that the provide and inject functions should be used in the setup function of the components. Also, the parent component and child component should be in the same component tree for inject to work.
It's important to use provide and inject sparingly and only for data that truly needs to be shared across multiple components. Overusing them can make the code harder to understand and maintain
原文地址: https://www.cveoy.top/t/topic/it5C 著作权归作者所有。请勿转载和采集!