Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue 3 get current application instance

Tags:

vue.js

How to access to current instance of application inside a component?

like image 220
Rex Pan Avatar asked Apr 17 '26 01:04

Rex Pan


2 Answers

Option 1: Create a plugin

// define a plugin
const key = "__CURRENT_APP__"
export const ProvideAppPlugin = {
    install(app, options) {
        app.provide(key, app)
    }
}
export function useCurrentApp() { 
    return inject(key) 
}

// when create app use the plugin
createApp().use(ProvideAppPlugin)

// get app instance in Component.vue
const app = useCurrentApp()
return () => h(app.version)

Option 2: use the internal api getCurrentInstance

import { getCurrentInstance } from "vue"
export function useCurrentApp() {
    return getCurrentInstance().appContext.app
}

// in Component.vue
const app = useCurrentApp()
like image 98
Rex Pan Avatar answered Apr 20 '26 09:04

Rex Pan


getCurrentInstance() mentioned in other answers works in both Composition API and Options API, but there's also an undocumented way to access it in the Options API:

import { getCurrentInstance } from 'vue'

export default {
  mounted() {
    // these two should be the same
    console.log(getCurrentInstance().appContext)
    console.log(this.$.appContext)
  }
}

Vue playground link

The documentation used to say getCurrentInstance() only works in setup and lifecycle hooks, but it's been removed from the current documentation because it's an internal api you're not supposed to use. If you call the function during an event handler for example, it doesn't work. However this.$ still works.

export default {
  methods: {
    test() {
      console.log(getCurrentInstance()?.appContext) // undefined
      console.log(this.$.appContext) // defined
    },
  },
}

Vue playground link

I think either of these is subject to break in future Vue releases, and the provide/inject approach posted in another answer is the more reliable way to go.

like image 29
amitp Avatar answered Apr 20 '26 09:04

amitp