I have an ancestor Vue 2 component that uses provide
/inject
to inject a function from the ancestor to any nested (descendant) component. However I'm finding that inside that function this
is not bound to the ancestor but to the descendant.
How can I get a reference the ancestor from inside the injected function onCallback()
?
Example:
<template>
<Intermediary />
</template>
<script>
export default {
name: "Ancestor",
props: ["val"],
provide: {
onCallback() {
console.log(this.val); // <<< fails as `this` is bound to caller component
}
}
}
</script>
<template>
<Descendant />
</template>
<script>
export default {
name: "Intermediary"
}
</script>
<template>
<button @click="onCallback">Click Me!</button>
</template>
<script>
export default {
name: "Descendant",
inject["onCallback"]
}
</script>
CodePudding user response:
You can use function syntax to access this
, import computed
at the top and re-write provide
like:
provide() {
return {
onCallback: computed(() => () => console.log(this.val))
}
}
Do note that using function syntax doesn't make injected variables reactive by default. You need to use computed
to make them reactive. I highly recommend to go through this official doc to understand the concept correctly.
CodePudding user response:
The main thing I originally missed was that provide()
can be a function that is always bound to the ancestor component.
<template>
<Intermediary />
</template>
<script>
export default {
name: "Ancestor",
props: ["val"],
provide() {
return {
onCallback() {
console.log(this.val);
}
}
}
}
</script>