[Vuejs]-VueJS how to import and load components dynamically as a list is rendered

0👍

Dynamic imports use Promise internally, whereas computed property takes a factory function — so, yes, as a function it does actually accept parameters. For this to work, though, you’re gonna want to use require instead.

computed: {
  getComponent() {
    const componentsList = {
      jurisdictionEvidenceCount: '/chart/export_control/JurisdictionEvidenceCount.vue',
      grniSummary: '/data/finance/GRNISummary.vue'
    }

    return component => require(`@/components` + componentsList[component]);
  }
}

BTW, if you included vue in the resolve.extensions, that actually allows you to drop the extension type while importing a component. (Vue CLI should do this for you by default). Or you could confirm it by running:

vue inspect resolve.extensions

Here are my proposed changes anyway:

computed: {
  getComponent() {
    // Perhaps move this somewhere else though
    const componentsList = {
      jurisdictionEvidenceCount: 'chart/export_control/JurisdictionEvidenceCount',
      grniSummary: 'data/finance/GRNISummary'
    }

    return componentName => require(`@/components/${componentsList[componentName]}`);
  }
}

Leave a comment