vue-vite动态组件导入



我正在将现有的laravel ineria从mix迁移到vit。

我完成了迁移指南中的所有步骤,除了一件事之外,一切都很好。

我有一个组件接收一个包含组件数组的道具。

我曾经要求他们这样(在一个循环内(

...
this.$options.components[component_name] = require(`@/Pages/Components/Inputs/${component_name}`).default
...

这不适用于vite,因为">需要";,我必须用导入替换它

所以我尝试了这些方法,但都不起作用

this.$options.components[component_name] = () => resolvePageComponent(`./Pages/Components/Inputs/${component_name}.vue`, import.meta.glob('./Pages/**/*.vue'))

this.$options.components[component_name] = () => resolvePageComponent(`@/Pages/Components/Inputs/${component_name}.vue`, import.meta.glob('./Pages/**/*.vue'))
this.$options.components[component_name] = resolvePageComponent(`./Pages/Components/Inputs/${component_name}.vue`, import.meta.glob('./Pages/**/*.vue'))
this.$options.components[component_name] = resolvePageComponent(`@/Pages/Components/Inputs/${component_name}.vue`, import.meta.glob('./Pages/**/*.vue'))

他们都抛出了相同的异常

"Uncaught (in promise) Error: Page not found: ./Pages/Components/Inputs/Text.vue".

所以,这就是我解决它的方法。

你需要导入这个

import {defineAsyncComponent} from "vue";

在数据上,定义这是一个空数组

layout_components: []

在创建或安装的上,您需要定义此

mounted() {
this.layout_components = Object.keys(this.$options.components)
this.layouts.forEach(layout => this.importLayoutComponent(layout))
}

这将获得您正在使用的组件,并将它们添加到阵列中

最后,

我创建了这个方法来动态导入组件

importLayoutComponent(layout) {
if (!this.layout_components.includes(layout.name)) {
this.layout_components.push(layout.name)
this.$options.components[layout.name] = defineAsyncComponent(() => import(`../Sections/${layout.type}/${layout.name}.vue`))
}
}

在我的html模板中

<component
:is="layout.name"
... //other propes to pass to the component
/>

注意:您需要像这样编写组件的路径"/组件"路径">

最新更新