I am currently developing a VueJS 3 library using the Composition API. I have implemented Provide/Inject as outlined in the documentation. However, I am encountering an issue where the property in the child component remains undefined, leading to the following error in the browser console:
https://i.stack.imgur.com/2Y6jw.png
Below is a simplified version of my code:
Usage In Project
<ThemeProvider>
<Button color="green">
ABC
</Button>
</ThemeProvider>
<script>
import { ThemeProvider, Button } from 'my-library'
export default {
name: 'SomePage',
setup() {...},
}
</script>
ThemeProvider.js (Parent Component)
import { toRefs, reactive, provide, h } from 'vue'
export default {
name: 'theme-provider',
props:
theme: {
type: Object,
default: () => ({...}),
},
},
setup(props, { slots }) {
const { theme } = toRefs(props)
provide('theme', reactive(theme.value))
return () =>
h(
'div',
{...},
slots.default()
)
},
}
Button.js (Child Component)
import { inject, h } from 'vue'
export default {
name: 'Button',
setup(props, { slots }) {
const theme = inject('theme')
console.log(theme) // returns undefined
return () =>
h(
'button',
{...},
slots.default()
)
},
}