`Provide / Inject ` provided to current component
What problem does this feature solve?
Can't Gets the provided data by the current component in a deep hook function. Only parameters can be passed
const useHook = (location) => {
console.log(inject('location')) // undefined
const { some } = useOther(location)
return {
some
}
}
const parent = {
setup() {
// provide('location', 'North Pole')
const location = 'North Pole'
provide('location', location)
const {sub} = useHook(location)
return {
sub
}
}
}
A large number of business scenarios are assembled using hook functions, and even deeply used and reused, avoiding parameter layer transfer if the data exposed by the current component can be obtained.
大量的业务场景都使用勾子函数组装,甚至会深层次使用以及复用,如果可以取到当前组件暴露的数据,就避免使用参数层层传递
What does the proposed API look like?
Gets the provid data by the current component in a deep hook function. similar to #4809
// functional component
const sub = () => {
const location = inject('location', 'unknow')
return h('div', null, 'this location is' + location)
}
// hooks
const useWork = () => {
const location = inject('location', 'unknow')
// do something...
retrun { ... }
}
const parent = {
setup() {
provide('location', 'North Pole')
const { some } = useWork()
return {
some,
sub
}
}
}
Provide gives a variable to the children, not the current instance and this is by design as otherwise it would overwrite existing properties.
You may take a look in #4778
I think at this moment you can use pinia
for such purpose.