[Vuejs]-Vue 3 get current application instance

2👍

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()

1👍

In Vue.js version 3, you can access the current instance of an application inside a component using the getCurrentInstance() function provided by the Composition API.

Here’s an example:

import { getCurrentInstance } from 'vue'

export default {
  mounted() {
    const app = getCurrentInstance()
    console.log(app.appContext.app) // This will log the current instance of the application
  }
}

Note that getCurrentInstance() should only be used in very specific situations where it’s necessary to access the instance. In general, it’s recommended to use the Composition API’s reactive properties and methods to manage state and actions inside a component.

Leave a comment