Is there in Vue.js something like createContext in React? https://flaviocopes.com/react-context-api/
I found this https://github.com/zephraph/vue-context-api but I would prefer to use something more “official”
The most similar thing Vue has to React's contexts is the Provide / Inject options, also available in Vue 2.
In fact it was initially designed after React contexts.
The usage in vue requires defining a provide
property on the ancestor component and an inject
property on the descendant.
Vue.component('ancestor', {
template: '<div>Ancestor: <slot></slot></div>',
provide: {
providedKey: 123
}
})
Vue.component('descendant', {
template: '<div>Descendant of {{ancestorData}}</div>',
inject: {
ancestorData: 'providedKey'
}
})
Then you can do:
<ancestor>
<descendant />
<descendant />
<descendant />
</ancestor>
And it also works for deeply nested components, they don't need to be direct descendants.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With