Vue Vite 动态组件导入

5

我正在将一个现有的laravel惯性应用从mix迁移到vit。

我按照迁移指南中的所有步骤操作,一切都正常工作,除了一个问题。

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

以前我在循环内部这样要求它们:

...

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

...

由于"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'))

所有这些都抛出相同的异常。

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

你解决过这个问题吗? - ii iml0sto1
很遗憾,我在这个问题解决之前无法搬到vite。 - Moauya Meghari
每当我解决了,我会在这里回答问题。 - Moauya Meghari
@iiiml0sto1,如果你还需要的话,查看这个问题的答案! - Moauya Meghari
1个回答

0
所以,这是我解决问题的方法。
你需要导入这个。
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
/>

注意:你需要像这样写组件的路径 "../path-to-component"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接