Commit cd49756c by zhuxichen

demo 支持从远程获取组件,检测mode为remote时减少getConfig消耗

parent 3d5fd1d1
......@@ -3,7 +3,7 @@
import { ComponentCustomProperties } from 'vue'
// 定义 $globalConfig 的接口
interface GlobalConfig {
export interface GlobalConfig {
componentKV: Record<string, string>
[v: string]: string | object
}
......
......@@ -8,22 +8,23 @@
</template>
<script setup lang="ts">
import {
ref,
onMounted,
defineAsyncComponent,
defineProps,
getCurrentInstance,
} from 'vue'
const props = defineProps<{
import { useConfig } from '@/config/useConfig'
import { ref, onMounted, defineAsyncComponent, defineProps } from 'vue'
interface Props {
componentKey: string // 组件键
}>()
// local请求本地的key remote请求接口的key
componentType: 'local' | 'remote'
}
const props = withDefaults(defineProps<Props>(), {
componentType: 'local',
})
const instance = getCurrentInstance()
const globalConfig = ref<Record<string, string | object> | undefined>(undefined)
const DynamicComponent = ref(null)
const { fetchGlobalConfig } = useConfig()
// 动态导入组件
const loadComponent = async (componentPath: string) => {
DynamicComponent.value = defineAsyncComponent(
......@@ -31,20 +32,25 @@ const loadComponent = async (componentPath: string) => {
)
}
// 获取全局配置和动态组件路径
const fetchRmoteComponentPath = async () => {
return Promise.resolve('/src/components/testComponent/TestCom1.vue')
}
// 区分组件类型,以获取组件路径【全局 / 远程】
const fetchGlobalConfigAndComponentPath = async () => {
globalConfig.value =
instance?.appContext.config.globalProperties.$globalConfig
const componentKV = (globalConfig.value?.componentKV || {}) as Record<
string,
string
>
// 可以是一个await 来接受componentPath
const componentPath = componentKV?.[props.componentKey]
let componentPath: string | undefined
if (props.componentType === 'local') {
const res = await fetchGlobalConfig()
componentPath = res?.componentKV?.[props.componentKey]
} else {
componentPath = await fetchRmoteComponentPath()
}
if (componentPath) {
loadComponent(componentPath)
} else {
console.warn(`Component path not found for key: ${props.componentKey}`)
console.warn(
`Component path with ${props.componentType} not found for key: ${props.componentKey}`,
)
}
}
......
import type { GlobalConfig } from 'env'
import { ref, getCurrentInstance } from 'vue'
export const useConfig = () => {
const instance = getCurrentInstance()
const globalConfig = ref<GlobalConfig>()
const fetchGlobalConfig = () => {
if (instance) {
globalConfig.value =
instance.appContext.config.globalProperties.$globalConfig
}
return Promise.resolve(globalConfig.value)
}
return { globalConfig, fetchGlobalConfig }
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment