Home > Mobile >  How to create dynamic components in vueJS
How to create dynamic components in vueJS

Time:03-05

I am new to vueJS and am trying to load components dynamically. I searched on the web and experimented with many suggestions but am still not able to get it to work.

Scenario: I want to have a 'shell' component that acts as a container for swapping in and out other components based on user's selection. The file names of these components will be served up from a database

Here's the shell component:

    <template>
    <keep-alive>
        <component :is='compName'></component>
    </keep-alive>
</template>

<script>
    props: ['vueFile'],

    export default ({
        data() {
            compName: ()=> import('DefaultPage.vue')
        },

        watch: {
            compName() {
                return ()=> import(this.vueFile);
            }
        }

    })
</script>

This does not work.

If I hard code the component file name, it works correctly... e.g.

return ()=> import('MyComponent.vue');

The moment I change the import statement to use a variable, it gives an error even though the variable contains the same string I hard code.

What am I doing wrong?

CodePudding user response:

compName() {

     const MyComponent = () => import("~/components/MyComponent.js");
}

You can see this post https://vuedose.tips/dynamic-imports-in-vue-js-for-better-performance

CodePudding user response:

try this

compName () {
  return ()=> import(`./component/${this.vueFile}`);
}

The import() must contain at least some information about where the module is located. https://webpack.js.org/api/module-methods/#dynamic-expressions-in-import

  • Related