Satyajyoti Biswas
Satyajyoti Biswas

Reputation: 927

Vue Component Import

I know this question has been asked several times, unfortunately i can't figure it out. My question is how to import all vue single file components from a directory in one shot. Le'me clear that..

Say i have directory named as Add/Items where i stored all vue components, ItemA, ItemB and so on. I want to import these components to a Add.vue file which is sitting just outside the Add directory.

I have tried these methods (in Add.vue file script section) .. Method #1:

import ItemA from './Add/Items/ItemA'
import ItemB from './Add/Items/ItemB'

export default {
  components: {
   'item-a': ItemA,
   'item-b': ItemB
  }
}

and it works, with <item-a/> as well as with <component is="item-a"/>

but the following method does not work.

Method #2

Here i have created a file named index.js at Add/Items directory where the following snippet is written

import itemA from './ItemA'
import ItemB from './ItemB'

export default {
  ItemA,
  ItemB
}

and in the Add.vue file

import items from './Add/Items'

export default {
  components: {
    items
  }
}

And it is working neither with <item-a/> nor with <component is="item-a"/>. Is there something i m missing ?? and by the way, <component :is="item-a"/> is my preference.

Thanks in advance.

Upvotes: 0

Views: 234

Answers (1)

Max Sinev
Max Sinev

Reputation: 6034

In last example(Add.vue) in your question you will get this(that is not what you want):

  components: {
    items: {
      ItemA,
      ItemB
    }
  }

You just need to use spread(...) operator or assign items to components directly:

export default {
  components: {
    ...items
  }
}

OR this:

export default {
  components: items
}

Upvotes: 2

Related Questions