vue vite动态组件导入

Moa*_*ari 5 inertiajs laravel vue.js vuejs3 vite

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

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

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

我曾经这样要求它们(在循环内)

...

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

...
Run Code Online (Sandbox Code Playgroud)

由于“ require ”,这不适用于 vite,我必须将其替换为import

所以我尝试了这些方法,但没有一个有效

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'))
Run Code Online (Sandbox Code Playgroud)

他们都抛出相同的异常

"Uncaught (in promise) Error: Page not found: ./Pages/Components/Inputs/Text.vue".
Run Code Online (Sandbox Code Playgroud)

Moa*_*ari 0

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

你需要导入这个

import {defineAsyncComponent} from "vue";
Run Code Online (Sandbox Code Playgroud)

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

layout_components: []
Run Code Online (Sandbox Code Playgroud)

在创建或安装时,您需要定义它

mounted() {
    this.layout_components = Object.keys(this.$options.components)
    this.layouts.forEach(layout => this.importLayoutComponent(layout))
}
Run Code Online (Sandbox Code Playgroud)

这将获取您正在使用的组件并将它们添加到数组中

最后,

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

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`))
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的 html 模板中

<component
  :is="layout.name"
  ... //other propes to pass to the component
/>
Run Code Online (Sandbox Code Playgroud)

注意:您需要像这样编写组件的路径“../path-to-component”