Reactivity Transform not working with provide/inject
Vue version
3.2
Link to minimal reproduction
Steps to reproduce
Using provide/inject using Reactivity Transforms such as $ref and $computed doesn't work the same as without the transform (ref.value, computed.value,...etc)
What is expected?
Expected to be able to reference a provided/injected reference to a $ref
or $computed
property from parent component in child component.
What is actually happening?
The reference doesn't work. Although when tried the same example with ref
and computed
properties and using the .value
in the child everything worked just fine.
System Info
No response
Any additional comments?
No response
Please read the docs carefully - https://vuejs.org/guide/extras/reactivity-transform.html#retaining-reactivity-across-function-boundaries
Your first issue is in Canvas.vue where you actually provide value of the ref/computed property instead of ref/computed object itself. That's why you have to use $$()
provide('canvas', $$(canvas))
provide('ctx', $$(ctx))
The second problem is with the way you use injected values in Circle.vue.
const ctx = inject('ctx')
watchEffect(() => {
if (ctx) {
}
})
Here, ctx is a ref object but you do not use .value explicitly. Once again you have to use $()
to tell the compiler that you want to treat this variable as a ref.
const canvas = $(inject('canvas'))
const ctx = $(inject('ctx'))