DEV Community

The Magic of Vue's Dynamic Components For Lists of Data

Drew Town on June 29, 2019

View this article and others like it on drewtown.dev Vue's Dynamic components are one of the most underutilized superpowers of Vue. They allow de...
Collapse
 
alexparra profile image
Alex Parra

I really like this.
And you can also use v-bind to pass an object thus passing multiple props in a compact way or even a calculated way dependent on the item type. Same for event listeners with v-on.

Collapse
 
drewtownchi profile image
Drew Town

Exactly! I did this in the project I was working on but wanted to keep the example simple. Thanks for the reply 😊

Collapse
 
akselsoft profile image
Andrew MacNeill

In the above scenario, don't you still have to do an "import" in the script and components in the export default script?

I'm trying to avoid having to do an explicit import but still have the components generated dynamically with something like
computed: {
dynamicComponent () {
var x = this.compMe.trim().replace('components/', '')
return () => import(components/${x})
}
}

The problem is that since it's computed, it only ever gets the final component.

Any ideas?

Collapse
 
marcellothearcane profile image
marcellothearcane

Could you explain a bit more? Is <component> a special Vue thing, and the actual component file is whatever is rendered into :is=""?

Collapse
 
anduser96 profile image
Andrei Gatej

As far as I know, if you provide a string for the isproperty, it would search through the registered components and will try to find the component, depending on the name that you provided.

The is property also accepts a promise as a value. When would you use a promise? Here is a small demo I wrote a while ago. If you go this route, you do not have to register your components in the
components property.