I'm running into an issue with Vue 3 (alpha 4):
Inside the setup()
function I am trying to read the parent component. As per the documentation on https://vue-composition-api-rfc.netlify.com/api.html#setup it should expose the parent via the context
argument, either as a property of context.attrs or directly as parent (see the SetupContext
bit under 'typing'). I don't find the documentation to be very clear on whether parent
should be accessed directly from SetupContext
, or via SetupContext.attrs
, so I've tried both ways, but to no avail.
Here's my issue, I can access the SetupContext
and SetupContext.attrs
(which is a Proxy) just fine when logging them. SetupContext.attrs
exposes the usual proxy properties ([[Handler]]
, [[Target]]
and [[IsRevoked]]
) and when inspecting [[Target]]
it clearly shows the parent property.
When logging the parent though, it just prints out undefined:
export default {
setup(props, context) {
console.log(context);
// Output: {attrs: Proxy, slots: Proxy, emit: ƒ}
console.log(context.attrs);
// Output: Proxy {vnode: {…}, parent: {…}, appContext: {…}, type: {…}, root: {…}, …}
console.log(context.attrs.parent);
// Output: undefined
}
};
Spreading the context yields the same result:
export default {
setup(props, { attrs, parent }) {
console.log(attrs);
// Output: Proxy {vnode: {…}, parent: {…}, appContext: {…}, type: {…}, root: {…}, …}
console.log(attrs.parent);
// Output: undefined
console.log(parent);
// Output: undefined
}
};
I'm a bit new to proxies in JavaScript, but from what I've read on them, and from experimenting with proxies returned by reactive() for example. I should just be able to access the property like I normally would with an object. Any ideas on what I'm doing wrong?
I've created a codesandbox to reproduce the problem
You can use getCurrentInstance
. It is undocumented Vue feature.
Usage is as easy as:
import { getCurrentInstance } from "vue";
export default {
setup(props) {
const instance = getCurrentInstance();
console.log("parent:");
console.log(instance.parent);
}
}
Vue considers it an internal api and warns against using it. For your consideration, you can read this github issue and this documentation from wayback machine.
Also, probably worth noting that Vue composition api plugin exposes parent in the same way, but it is referenced as instance.$parent
there.