How to async import all Vue3 components?

Viewed 886

I'm trying to make the components work. I want to have component names in the array, then import components as async and then somehow put the variable into app.component. I've been trying for about 6 hours here and I can't figure it out. I don't want to have 50x import and 50x app.component for each component and it doesn't want to work for me I'm probably missing something obvious. Unfortunately, I'm not that good at JS.

main.js

import { createApp, defineAsyncComponent } from "vue";
import App from "./App.vue";
import router from "./router";

var subComponents = new Array([
  "test", 
  "test2"
]);  

subComponents.forEach(subComponent => {
  subComponent = defineAsyncComponent(() =>
    import(`@/components/sub/${subComponent}.vue`)       
  )
});

const app = createApp(App);

app.use(router);
app.component(subComponent, subComponents);
app.mount("#app");

It reports these problems

Failed to resolve component: test

Failed to resolve component: test2

1 Answers

I think what you need is to register each component individually inside the loop like this:

subComponents.js:

const subComponents = ['test', 'test2'];

export { subComponents }

main.js:

import { createApp, defineAsyncComponent } from 'vue';
import App from './App.vue';
import router from './router';
import { subComponents } from './subComponents';

const app = createApp(App);

subComponents.forEach(subComponent => {
    const component = defineAsyncComponent(() => import(`@/components/sub/${subComponent}.vue`));

    app.component(subComponent, component);
});

app.use(router);
app.mount('#app');

At the moment you're passing a non-existent subComponent variable as the first argument to a single instance of app.component and the array as the second argument.

app.component should be used for a single component, the first argument being the components' name, the second being the component itself.

So, if you loop through your array of names and import each component using that name, then register a component using the name and imported component, they'll be available throughout your app.

Related