如何访问组件内的应用程序的当前实例?
// 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)
getCurrentInstance
import { getCurrentInstance } from "vue"
export function useCurrentApp() {
return getCurrentInstance().appContext.app
}
// in Component.vue
const app = useCurrentApp()
在 Vue.js 版本 3 中,您可以使用 Composition API 提供的 getCurrentInstance() 函数访问组件内应用程序的当前实例。
这是一个例子:
import { getCurrentInstance } from 'vue'
export default {
mounted() {
const app = getCurrentInstance()
console.log(app.appContext.app) // This will log the current instance of the application
}
}
请注意,getCurrentInstance() 只能在需要访问实例的非常特定的情况下使用。一般来说,建议使用 Composition API 的反应式属性和方法来管理组件内的状态和操作。
getCurrentInstance()
在Composition API和Options API中都适用,但在Options API中还有一种未记录的方式来访问它:
import { getCurrentInstance } from 'vue'
export default {
mounted() {
// these two should be the same
console.log(getCurrentInstance().appContext)
console.log(this.$.appContext)
}
}
文档曾经说过 getCurrentInstance() 仅适用于设置和生命周期挂钩,但它已从当前文档中删除,因为它是您不应该使用的内部 api。例如,如果您在事件处理程序期间调用该函数,它将不起作用。然而
this.$
仍然有效。
export default {
methods: {
test() {
console.log(getCurrentInstance()?.appContext) // undefined
console.log(this.$.appContext) // defined
},
},
}
我认为其中任何一个都可能在未来的 Vue 版本中受到破坏,而另一个答案中发布的提供/注入方法是更可靠的方法。