As written in the subject,
in vue,
provide is used for passing data from parent to child.
and child element gets the data by inject.
as @emit does, is it also possible to modify data given by "provide" in child element?
Thank you.
Yes, a component could provide
a ref
that gets updated by a descendant that inject
s it:
// App.vue
export default {
setup() {
const counter = ref(0)
provide('counter', counter)
}
}
// ComponentA.vue
export default {
setup() {
const counter = inject('counter')
return {
counter,
increment: () => counter.value++ // updates App.counter
}
}
}
demo 1
However, the Vue docs recommend also provide
-ing an update method, keeping the mutation and state co-located:
// App.vue
export default {
setup() {
const counter = ref(0)
provide('counter', counter)
provide('increment', () => counter.value++)
}
}
// ComponentA.vue
export default {
setup() {
return {
counter: inject('counter'),
increment: inject('increment'),
}
}
}
demo 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With