异步获取组件
@niu-tools/vue3
test
<script setup lang="ts">
import { useAsyncComponent } from '@niu-tools/vue3'
import TestComp from './test.vue'
const AsyncComponent = useAsyncComponent(TestComp)
</script>
<template>
<div>
<AsyncComponent></AsyncComponent>
</div>
</template>
<script setup lang="ts">
import { useAsyncComponent } from '@niu-tools/vue3'
import TestComp from './test.vue'
const AsyncComponent = useAsyncComponent(TestComp)
</script>
<template>
<div>
<AsyncComponent></AsyncComponent>
</div>
</template>
源码
查看源码
useAsyncComponent/index.ts源码
ts
export * from "./useAsyncComponent"
export * from "./useAsyncComponent"
useAsyncComponent/useAsyncComponent.ts源码
ts
import { Component, defineAsyncComponent, defineComponent, h } from "vue"
function loadingComponent() {
return h("div", {
style: {
textAlign: "center",
paddingTop: "20px"
}
},
["加载中..."]);
}
const emptyComponent = defineComponent({
name: 'EmptyComponent',
render() {
return h("div", null, "空")
}
})
const componentLoader = (comp: Component) => () =>
new Promise<any>(async resolve => {
const [compont] = await Promise.all([
comp,
new Promise(re => {
setTimeout(async () => {
re(0)
}, 2000)
}),
])
resolve(compont)
})
export function useAsyncComponent(comp: Component) {
return defineAsyncComponent({
loader: componentLoader(comp),
loadingComponent: loadingComponent,
})
}
import { Component, defineAsyncComponent, defineComponent, h } from "vue"
function loadingComponent() {
return h("div", {
style: {
textAlign: "center",
paddingTop: "20px"
}
},
["加载中..."]);
}
const emptyComponent = defineComponent({
name: 'EmptyComponent',
render() {
return h("div", null, "空")
}
})
const componentLoader = (comp: Component) => () =>
new Promise<any>(async resolve => {
const [compont] = await Promise.all([
comp,
new Promise(re => {
setTimeout(async () => {
re(0)
}, 2000)
}),
])
resolve(compont)
})
export function useAsyncComponent(comp: Component) {
return defineAsyncComponent({
loader: componentLoader(comp),
loadingComponent: loadingComponent,
})
}