Overall goal: from a child Vue component, get access to the component that it is imported and used within – which is not always the same as $parent
. This should be done by only making changes within the child component (if possible).
We have PinButton
Vue component meant to add a “pinning” functionality to other components. This component is used within many other components and we want to be able to access the parent props so they can be saved and rendered on a different page of “pinned content” by passing those props back into the parent component.
Note: I know this would be possible by manually passing the parent props down into the component (<pin-button :parent-props="$props" />
), but we’re trying to avoid having to do this every time the component is used.
A minimal reproduction of this with a single parent and child component will show that you can access parent props using $parent.$props
. However, when the child component is nested as slot content of some other component within the parent, then the child will get the props of the wrapper component – not the component in which it is imported and actually used.
Sandbox reproduction – I want to get the props for ParentComponent
from within ChildComponent
. The expected value is shown by passing the props along (what I’m trying to avoid) and the actual value is the props of the SlotWrapper
component, which doesn’t import ChildComponent
so I wouldn’t consider it the true parent, but it is the direct parent element in the <template>
Update: Seems like the suggested solution for “arbitrarily deep” access is provide/inject, but this would still seem to require changing all components that use the
<pin-button />
Advertisement
Answer
To answer your question directly, you can access ParentComponent from ChildComponent via the “context” the component is rendered within:
// ChildComponent.vue computed: { expectedProps() { return this.$vnode.context.$props } }
But this might be an “XY” kind of problem; I’m sure there’s a better design solution for what you’re trying to achieve.