Vue.js 中有类似 React 中的 createContext 的东西吗?

Rap*_*l10 11 reactjs vue.js

Vue.js 中有类似 React 中的 createContext 的东西吗?https://flaviocopes.com/react-context-api/

\n

我找到了这个https://github.com/zephraph/vue-context-api但我更喜欢使用更多 \xe2\x80\x9cofficial\xe2\x80\x9d

\n

Jen*_*ens 22

Vue 与 React 上下文最相似的地方是Provide / Inject选项,在Vue 2中也可用。

事实上它最初是在 React contexts 之后设计的

vue 中的使用需要provide在祖先组件上定义一个属性,inject在后代组件上定义一个属性。

Vue.component('ancestor', {
  template: '<div>Ancestor: <slot></slot></div>',
  provide: {
    providedKey: 123
  }
})

Vue.component('descendant', {
  template: '<div>Descendant of {{ancestorData}}</div>',
  inject: {
    ancestorData: 'providedKey'
  }
})
Run Code Online (Sandbox Code Playgroud)

然后你可以这样做:

<ancestor>
 <descendant />
 <descendant />
 <descendant />
</ancestor>
Run Code Online (Sandbox Code Playgroud)

它也适用于深度嵌套的组件,它们不需要是直接后代。