The inject API doesn't work inside default functions while prop type is Function
Version
3.2.11
Reproduction link
https://stackblitz.com/edit/vue-zbukp5?file=src%2Fcomponents%2FHelloWorld.vue
Steps to reproduce
https://v3.vuejs.org/guide/migration/props-default-this.html
It doesn't work and there is a warning:
[Vue warn]: inject() can only be used inside setup() or functional components.
What is expected?
It works well
What is actually happening?
It doesn't
export default {
name: 'HelloWorld',
props: {
msg: {
type: String,
default: () => inject(injectionKey)
},
setMsg: {
type: Function,
default: ()=>inject(fnInjectionKey),
}
},
setup(props) {
console.log(props.msg) // works as expected non Function type
console.log(props.setMsg ) // Function Type, return the wrapper instead of its result
console.log(props.setMsg() ) // xxx: evaluate default and return the result of inject
}
}
simple values can either be of the provided type or a function if it is function, vue evaluate it as a factory function for the default value.
with type Function and a value of type Function vue can not distinguish between factory function and an actual function being set as the value due to ambiguity .
The actual workaround for this use case is to NOT set a default in props, instead optionally inject the value in setup if the prop was not provided.