[Vuejs]-Dynamic load components from list of id

3👍

Take a look at https://v2.vuejs.org/v2/guide/components-dynamic-async.html#Async-Components

<template>
  <div>
    <component v-for="component in myComponents" :is="component"/>
  </div>
</template>

<script>
export default {
  data() {
    return {
      component_ids: ['select', 'input', 'modal']
    }
  },
  computed: {
    myComponents() {
      return this.component_ids.map(id => () => import(`@/components/${id}.vue`));
    }
  }
}
</html>

Obviously I used words instead of numeric IDs like you did, but this is just a matter of mapping IDs to component paths

When you look at the double lambda id => () => import('@/components/${id}.vue') you may be a little worried.

The point here is that we are mapping an array of strings to an array of functions that return a component.

<component :is="() => import('@/components/hello.vue)" would work

:is="import('@/components/hello.vue')" wouldn’t.

Leave a comment