Provide and Inject
provide allows a component to share its state with its descendants, while inject allows a component to access the state provided by its ancestors.
Here's an example of how to use provide and inject in a Vue.js application:
// Parent component //export default { name: 'Parent', provide() { return { theme: 'dark' } }, template: ` <div> <Child /> </div> `}
// Child componentexport default { name: 'Child', inject: ['theme'], template: ` <div :class="theme"> { { theme } } </div> `}
In this example, the Parent component is using the provide feature to make the theme property available to its descendants. The Child component is using the inject feature to access the theme property provided by its ancestor.
The inject option is an object that maps the name of the property to be injected (e.g. "theme") to the key of the property in the provide object. It can also be an array that contains the names of the properties to be injected.
It's important to notice that the provide and inject features are only available in the component's scope, not global.
Another way to use provide and inject is using the provide option in the component's options and inject option in the component's computed properties.
export default { name: 'Parent', provide: { theme: 'dark' }, template: ` <div> <Child /> </div> `}
export default { name: 'Child', computed: { ...inject('theme') }, template: ` <div :class="theme"> { { theme } } </div> `}
This way, the Child component can use the theme property as a computed property, so it can be reactive.