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

Viewed 5965
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.

Related