JavaScript/vue.js/getCurrentInstance

来自康健生活

标题文本

获取全局注册组件

最简单的方法是借助 window

window.app = app;

以及

document.querySelector('#app').__vue_app__

以上两种方法是可以在在外部的 js 文件中获取 vue 的 createApp 返回实例,通过实例(app.component(name))即可获取全局注册组件。

以下两种常规方法反而只能在 vue 文件中获取 vue 的实例。

<template>
  <EchartsLinePanel
    v-if="options"
    :layerOptions="options"
    @update:layerOptions="handleUpdateOptions"
  />
</template>

<script lang="ts" setup>
import { defineAsyncComponent, getCurrentInstance, type ComponentInternalInstance } from 'vue'

const { appContext } = <ComponentInternalInstance>getCurrentInstance()

const EchartsLinePanel = defineAsyncComponent({
  loader: async () => {
    // 获得 athena-echarts-line 组件
    return appContext.components['athena-echarts-line']
  },
})
</script>

另外一个思路

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

所以在这里补充一种借助事件总线的通用方法获取 vue 实例,某种程度上的说法是这种才是正解。

./src/events/bus.js
import mitt from 'mitt'

export const emitter = mitt()
export const useBus = () => ({ bus: emitter })
./src/main.js
import { createApp } from 'vue'
import { emitter } from './events/bus'

const app = createApp(App)
// ###
// 全局可用方法
// declare module '@vue/runtime-core' {
//   export interface ComponentCustomProperties {
//     emitter: typeof emitter
//   }
// }
app.config.globalProperties.$emitter = emitter

emitter.emit('appMounted', app)
export default app.mount('#app')

在其他 js 文件中使用,借助 js 文件的上下文

./src/store/action.js
import { useBus } from '@/events/bus.js'

let vueApp = null
useBus().bus.on('appMounted', (vm) => {
  console.log(vm)
  vueApp = vm
})

export default {
  async registryComponent({ commit, dispatch }, name) {
    try {
      console.log('vueApp', vueApp)
// ...