Subscribe on changes!

Production build - the getCurrentInstance().ctx not preserve the current component's data

avatar
May 14th 2022

Link to minimal reproduction

Sample Code

Steps to reproduce

I need to get the component data to handle other stuffs outside of Vue component, i get the current component by getCurrentInstance and pass the ctx prop to other function to get the isActive from it, everything is ok on development but on production the ctx doesn't contain isActive anymore , the code look something like this:

I'm using Vite@2.8.0 and Vue 3.x

// CRadio.vue
<script>
export default {
    name: "CRadio",
    inheritAttrs: false,
    props: {
        ...
    },
    setup(props, ctx) {
        const app = getCurrentInstance()
        const {
            isActive,
            isFocused,
        } = useSelection()

        useVariant(app)

        return {
            isFocused,
            isActive,
        }
    },
}
</script>
// variant.js
export function useVariant(app) {
    const app = getCurrentInstance()

    const classes = computed(() => {
        console.log(app.ctx); // doesn't contain isActive and isFocused on production build
    })

    return {
        classes,
    }
}

Please help!

Thanks!

What is expected?

the ctx of getCurrentInstance contains isActive

What is actually happening?

the ctx of getCurrentInstance doesn't contain isActive

System Info

No response

Any additional comments?

No response

avatar
May 14th 2022

You can do the same thing without using app.ctx, like this example. Also you can take a cue from naiveui.

avatar
May 14th 2022

This is an internal API. Using these is strongly discouraged and requires in-depth knowledge of Vue's internals.

In this case, comments in the source code tell us that this is the target for the public component proxy, which doesn't exist duriong prod for script-setup components because these are closed.

In short: Don't use this API, it's not doing what you want it to.

Don't use it.