0

I am having a problem when trying to dynamically use components in Vue 2. For example, I created a component that manages other components using . The problem is that when I try to pass an asynchronous component, it says that the module was not found, even though the module exists in the correct directory.

I ran the following tests to try to solve my problem.

load(){
const component = require(`${this.field.vuePath}`).default 
this.componentPath = component;
},
mounted(){
this.load();
}

template

.....
<component :is="componentPath" />

this variable this.field.vuePath has the path '@/views/BuilderHtml/Htmls/InfoCreate.vue' if show my files directories below: enter image description here

My file vue.config.js

const { defineConfig } = require('@vue/cli-service');
const NodePolyfillPlugin = require("node-polyfill-webpack-plugin");
const path = require('path');
const webpack = require('webpack');

let options = {
  transpileDependencies: true,
  devServer: {
    proxy:'http://localhost:9090',
    historyApiFallback: true
  },
  configureWebpack: {  
    plugins: [
      new NodePolyfillPlugin(),
      // new webpack.ProvidePlugin({
      //     // other modules
      //     introJs: ['intro.js', 'introJs']
      // })
    ],
    resolve: {
      alias: {
        '@': path.resolve(__dirname, 'src')
      }
    },
    optimization: {
      splitChunks: {
        chunks: "all",
      },
    },    
  },
  pluginOptions: {
    vuetober: {
      baseUrl: '/themes/theme-backend/assets',
    },
    i18n: {
      locale: 'pt-br',
      fallbackLocale: 'pt-br',
      localeDir: 'locales',
      enableInSFC: false,
      enableBridge: false
    }
  }
}


module.exports = defineConfig(options);

Error show:

Cannot find module '@/views/BuilderHtml/Htmls/InfoCreate.vue'
    at webpackContextResolve (src_components_Layout_FormView_FormFields_Fields_FieldRender_vue-src_components_Layout_FormVi-1cf622.js:1341:11)
    at webpackContext (src_components_Layout_FormView_FormFields_Fields_FieldRender_vue-src_components_Layout_FormVi-1cf622.js:1336:11)
    at VueComponent.loadDynamicComponents (Partial.vue?2049:26:1)
    at VueComponent.mounted (Partial.vue?2049:19:1)
    at invokeWithErrorHandling (vue.runtime.esm.js?c320:2987:1)
    at callHook$1 (vue.runtime.esm.js?c320:4000:1)
    at Object.insert (vue.runtime.esm.js?c320:4391:1)
    at invokeInsertHook (vue.runtime.esm.js?c320:6897:1)
    at VueComponent.patch [as __patch__] (vue.runtime.esm.js?c320:7108:1)
    at Vue._update (vue.runtime.esm.js?c320:3738:1)
Crazy
  • 346
  • 1
  • 4
  • 17

1 Answers1

0
const componentsMap = {
InfoCreate: () => import('@/views/BuilderHtml/Htmls/InfoCreate.vue')
}

selectComponent() {
   return componentsMap [this.type]
}

load(){
this.type= 'InfoCreate';
}

<component :is="selectComponent" />
张文玉
  • 29
  • 5