Subscribe on changes!

feat(app.runWithContext): Support `getCurrentInstance`

avatar
Jun 17th 2023

What problem does this feature solve?

When getCurrentInstance is used within app.runWithContext - top-level component instance should be returned (if it already exists). This should allow easier usage of Vue features outside components.

This behavior can currently be 'emulated' with app.provide, but it feels like there should be no need for this workaround.

runWithContext was first introduced in https://github.com/vuejs/core/pull/7451

What does the proposed API look like?

const app = createApp(App)
app.mount('#app')
app.runWithContext(() => {
  getCurrentInstance() === app._instance // true
})
avatar
Sep 28th 2023

The existing behavior is more flexible as it allows differentiating if you are running within a component + runWithContext().

If anything, I would say getCurrentInstance() should be null within runWithContext() but I think it's fine to keep the behavior unspecified. The goal of runWithContext()

The questions are: why do you need the app._instance for? Where are you accessing it right now given it's a private property that is only used for Devtools?

avatar
Sep 28th 2023

Well, given that, the following code does something illegal -

const app = v.createApp(
  v.defineComponent({
    setup() {
      const instance = v.getCurrentInstance()
      setTimeout(() => {
        console.log(instance === app._instance) // true
      })
    },
  })
)
app.mount('#app')

One might even argue that getCurrentInstance should not be allowed anywhere except for DevTools.

In all seriousness my use case is pretty much the same as for plugins. Except plugin installs require boilerplate code and, well, installing the plugin. While most of the time I just need to know under which Vue app my code currently runs. Specifically, I need access to created App, not app._instance, but without the inconvenience of exporting app or defining a plugin.

Actual usage of this for me involves classes and decorators, which would not make for a good example, however.

avatar
Sep 28th 2023

One might even argue that getCurrentInstance should not be allowed anywhere except for DevTools.

Not at all, it's actually pretty useful. It's used to know if we are in the context of a component's setup.

In all seriousness my use case is pretty much the same as for plugins. Except plugin installs require boilerplate code and, well, installing the plugin

I see. Then I think you should stick to plugins, it's better to not introduce yet another (and more obscure 😄 ) way of doing things. You get the current app directly on the plugin function's first argument. Unless there is something that cannot be achieved by plugins, this doesn't seem to be worth pursuing. If you find some, a well-defined use case would definitely help!