Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there in Vue.js something like createContext in React?

Tags:

reactjs

vue.js

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”

like image 933
Raphael10 Avatar asked Jan 25 '23 18:01

Raphael10


1 Answers

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.

like image 96
Jens Avatar answered Jan 27 '23 07:01

Jens