Use inject/provide in functionnal components #7521
-
In order to have generic and dynamically typed components, I'm trying to use inject and provide inside functional components but that seems not possible? Is this done on purpose or is this a bug? The point is to have generic components with typescript but here is a simple javascript reproduction: <script setup>
import { h, provide, inject } from 'vue'
const key = Symbol()
const Hello = (_, { slots }) => {
provide(key, "world")
return h('div', slots.default())
}
const Inside = () => {
const text = inject(key, "not found")
return h("div", text);
}
</script>
<template>
<Hello>
<Inside></Inside>
</Hello>
</template>
Edit: Seems like doing this instead works: <script setup>
import { h, provide, inject, defineComponent } from 'vue'
const key = Symbol()
const Hello = defineComponent((props, { slots }) => {
provide(key, "world")
return () => h('div', slots.default())
})
const Inside = () => {
const text = inject(key, "not found")
return h("div", text);
}
</script>
<template>
<Hello>
<Inside></Inside>
</Hello>
</template> I was under the impression that both syntax should be strictly equal. Is this caused by this section of the documentation? Functional components are an alternative form of component that don't have any state of their own. They act like pure functions: props in, vnodes out. They are rendered without creating a component instance (i.e. no this), and without the usual component lifecycle hooks. If so I think it should be noted more clearly that functionnal component have such limitations in the documation. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
The second variant does not create a functional component. it's a shortcut to creating a normal component, but passing just the setup function. That's why it works - it creates a stateful component.
We are open to suggestions in the core docs repository. As to why it doe not work: As functional components can't have (reactive) state, they only re-render when their props change (passed in by the re-rendering parent component. As |
Beta Was this translation helpful? Give feedback.
The second variant does not create a functional component. it's a shortcut to creating a normal component, but passing just the setup function. That's why it works - it creates a stateful component.
We are open to suggestions in the core docs repository.
As to why it doe not work: As functional components can't have (reactive) state, they only re-render when their props change (passed in by the re-rendering parent component. As
inject()
is not props, b…