E
E
Evgeny Zhurov2021-10-06 14:38:21
webpack
Evgeny Zhurov, 2021-10-06 14:38:21

How to dynamically load a Vue component?

I try this way:

<component :is="componentInstance" />

export default {
    props: {
        component_path: {
            type: String // напр., '@views/Accounts/SectionCreate', в webpack.mix.js есть alias '@views': path.join(__dirname, 'resources/js/views')
        }
    },

    computed: {
        componentInstance() {
            return () => import(`${this.component_path}.vue`)
            // Вариант: return () => import(`${this.component_path}.vue`).then(x => x.default)
        }
    }
}


I am getting an error:
[Vue warn]: Failed to resolve async component: function () {
        return __webpack_require__("./resources/js/components lazy recursive ^.*\\.vue$")("".concat(_this.component_path, ".vue")).then(function (x) {
          return x["default"];
        });
      }
Reason: Error: Cannot find module '@views/Accounts/SectionCreate.vue'


I don’t really understand where it comes from in the error ./resources/js/components, and why he even tries to climb into this folder, because. I don't give any instructions.

Google often recommends adding to webpack.mix.js: mix.webpackConfig.output.publicPath = '/'. Does not help.

I suspect that the issue is really in the webpack.mix configuration, since in another project on nodejs the similar code works. Can, who faced? how did you decide?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Anton, 2021-10-06
@Fragster

It seems that dynamic import only works for specific folders, so you need something like

import(`path/to/dynamic/components/${this.component_name}.vue`)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question