Vue3+Vite+TS项目 Component动态引入组件
***值得注意的点是ref的名称和is绑定的值不要一样,不然会出现警告和不显示组件的情况**
<template>
<div>
<component v-if="queryParams.formType == 'static' && form" ref="formData :is=" form"></component>
</div>
</template>
<script name="TaskForm" setup>
import { defineAsyncComponent, shallowRef } from 'vue'
const { proxy } = getCurrentInstance();
const viewsModules = import.meta.glob('@/views/**/*.{vue, tsx}');
const dynamicViewsModules = Object.assign({}, { ...viewsModules });
const queryParams = ref({});
const form = shallowRef(null);
const initData = () => {
queryParams.value = { ...proxy?.$route.query };
// 自定义组件
if (queryParams.value.formType == 'static') {
form.value = defineAsyncComponent(dynamicViewsModules[`/src/views${queryParams.value.formUrl}` + ".vue"])
}
}
initData();
</script>
如果出现“ TypeError: Cannot read properties of undefined (reading ‘__asyncLoader’)” / “Unhandled error during execution of scheduler” / “The above dynamic import cannot be analyzed by Vite” / “Component is missing template or render function”等情况(错误或者警告)上述代码都可以解决问题!!