How to access to current instance of application inside a component?
// 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)
getCurrentInstanceimport { getCurrentInstance } from "vue"
export function useCurrentApp() {
return getCurrentInstance().appContext.app
}
// in Component.vue
const app = useCurrentApp()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With